循环浏览子目录中的文件,将文件名附加为字典键



我在一个子目录/directory_name/中有一个文本文件目录。我想循环浏览这个子目录中的所有文件,并将文件名附加为字符串作为字典键。然后,我想取每个文本文件中的第一个单词,并将其用作每个键的值。我有点纠结于这个部分:

import os
os.path.expanduser(~/directory_name/)   # go to subdirectory
file_dict = {}  # create dictionary
for i in file_directory:
    file_dict[str(filename)] = {}  # creates keys based on each filename
    # do something here to get the dictionary values

有可能分两个单独的步骤来完成吗?也就是说,先创建字典键,然后对所有文本文件执行操作以提取值?

要更改目录,请使用os.chdir()。假设每个文件中的第一个单词后面跟着一个空格,

import os

file_dict = {}  # create a dictionary
os.chdir(os.path.join(os.path.expanduser('~'), directory_name))
for key in [file for file in os.listdir(os.getcwd()) if os.path.isfile(file)]:
    value = open(key).readlines()[0].split()[0]
    file_dict[key] = value

对我有效。如果你真的想分两步完成,

import os

os.chdir(os.path.join(os.path.expanduser('~'), directory_name))
keys = [file for file in os.listdir(os.getcwd()) if os.path.isfile(file)]  # step 1
# Do something else in here...
values = [open(key).readlines()[0].split()[0] for key in keys]  # step 2
file_dict = dict(zip(keys, values))  # Map values onto keys to create the dictionary

给出相同的输出。

相关内容

最新更新