有没有一种方法可以从循环的文件目录中动态地生成一个字典。

问题描述 投票:0回答:1

我有一些文件,像下面的目录中,我在循环处理每个目录。

  • tenents.txt
  • people.txt
  • customers.txt
  • clients'.txt

我试图动态地创建一个字典,像下面我有搜索高和下面,并尝试类似的例子在这里,但不能得到所需的输出。需要有人的帮助,以确定我做错了什么。

预期的输出。

[{'input' : 'tenents.txt' , 'config':'tenents.json'},{'input' : 'people.txt' , 'config':'people.json'}
 {'input' : 'customers.txt' , 'config':'customers.json'},{'input' : 'clients.txt' , 'config':'clients.json'}]

我的代码的实际输出。

[{'config': 'tenents.json','input': 'tenents.txt'}]
[{'config': 'people.json','input': 'people.txt'}]
[{'config': 'customers.json','input': 'customers.txt'}]
[{'config': 'clients.json','input': 'clients.txt'}]

另外,为什么键的顺序从左到右是错误的,为什么schema键在输入键之前,即使在我尝试排序之后。

这是我的代码中不能使用的片段。

import os
from pprint import pprint

filelist = []
for root, dirs, files in os.walk(path):
    for file in files:
        if file.endswith(".txt"):
            keys = ['input', 'config']
            filename = os.path.join(root, file)
            cname = filename.rstrip('.txt') + '.json'
            names = [[filename, cname]]

            filelist = [{k: v for k, v in zip(keys, n)} for n in names]
            pprint(filelist)

希望有人能帮帮我 我使用的是anaconda python 3。

python list loops file dictionary
1个回答
0
投票

下面的代码似乎可以工作。

file_list = []
for root, dirs, files in os.walk(path):
    for file in files:
        if file.endswith('.txt'):
            file_list.append({'input': file, 'config': file.replace('.txt', '.json')})
print(file_list)

我只是像你一样创建了一个文件列表 然后为每一个文件添加了一个包含各自值的字典.

© www.soinside.com 2019 - 2024. All rights reserved.