繁体   English   中英

从文件夹中读取文件并从文件中提取特定密钥并保存为 CSV 文件

[英]Read a file from a folder and extract a specific key from the file and save as in CSV file

我是 Python 的新手,我正在执行的任务是从特定目录中的.iris (包含嵌套字典格式列表)文件列表中提取特定键值。

我想提取特定值并将其另存为新的.csv文件,并对所有其他文件重复此操作。

下面是我的.iris文件示例,我应该只从中提取这些键('uid','enabled','login','name')

{"streamType":"user",
"uid":17182,
"enabled":true,
"login":"xyz",
"name":"abcdef",
"comment":"",
"authSms":"",
"email":"",
"phone":"",
"location":"",
"extraLdapOu":"",
"mand":997,
"global":{
"userAccount":"View",
"uid":"",
"retention":"No",
"enabled":"",
"messages":"Change"},
"grants":[{"mand":997,"role":1051,"passOnToSubMand":true}],

我正在尝试将.iris文件转换为.json并逐个读取文件,但不幸的是,我没有得到所需的确切 output。

拜托,任何人都可以帮助我吗?


我的代码(从评论中添加)

import os
import csv

path = ''
os.chdir(path) 

# Read iris File 
def read_iris_file(file_path): 
    with open(file_path, 'r') as f: 
        print(f.read())
        
# iterate through all files
for file in os.listdir():
    # Check whether file is in iris format or not
    if file.endswith(".iris"):
        file_path = f"{path}\{file}"
        # call read iris file function
        print(read_iris_file(file_path))   

试试下面的(这里的关键点是使用 ast 加载 iris 文件)

import ast

fields = ('uid','enabled','login','name')
with open('my.iris') as f1:
  data = ast.literal_eval(f1.read())
with open('my.csv','w') as f2:
  f2.write(','.join(fields) + '\n')
  f2.write(','.join(data[f] for f in fields) + '\n')

我的.csv

uid,enabled,login,name
17182,true,xyz,abcdef

您的文件包含 JSON 格式的数据,因此我们可以使用内置的json模块来解析它。 要迭代具有特定扩展名的文件,您可以使用pathlib.glob()和下一个模式"*.iris" 然后我们可以使用csv.DictWriter()并将"ignore"传递给extrasaction参数,这将使DictWriter忽略我们不需要的键,只写入我们传递给fieldnames参数的键。

代码:

import csv
import json
from pathlib import Path

path = Path(r"path/to/folder")
keys = "uid", "enabled", "login", "name"
with open(path / "result.csv", "w", newline="") as out_f:
    writer = csv.DictWriter(out_f, fieldnames=keys, extrasaction='ignore')
    writer.writeheader()
    for file in path.glob("*.iris"):
        with open(file) as inp_f:
            data = json.load(inp_f)
        writer.writerow(data)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM