python - 如何将文件名作为键和文件中的行作为列表制作字典?
问题描述
我在一个文件夹中有一堆 .txt 文件。文本文件看起来像
0 45 67 78 56
1 56 45 35 45
5 56 66 34 21
我只想要每行的第一个字符(例如,在这里我想要0
, 1
,5
并将它们存储在一个列表中,如[0,1,5]
)。现在我想将这些列表与文件名一起作为键值对存储在名为 classes 的字典中。类应如下所示:
classes={'Q.txt'=[0,1,1,9],
'T.txt'=[0,1],
...}
代码:
path = "C:/....../" # path to the folder
l=[]#empty list to store
classes={} # my dictionary
for filename in glob.glob(os.path.join(path, '*.txt')):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
for line in f.readlines():
l.append(int(line[0]))
classes[filename.split(os.sep)[1][:-4]]=l
现在我得到的是:
classses={'Q.txt': [0,0,1,1,9,0,1,............],
'T.txt': [0,0,1,1,9,0,1,............],
...}
这意味着当我只想让字典包含与相应文件名对应的列表时,它会附加所有文件中所有字符的整个列表。我该如何解决?
解决方案
所以你需要做的是l
在循环开始时重置。您可以使用os.path.basename
从完整路径中获取文件名。
path = "C:/....../" # path to the folder
classes={} # my dictionary
for filename in glob.glob(os.path.join(path, '*.txt')):
l=[]#empty list to store
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
for line in f:
l.append(int(line[0]))
classes[os.path.basename(filename)]=l