【问题标题】:How do I make a dictionary out of filenames as key and lines in the file as list?如何将文件名作为键和文件中的行作为列表制作字典?
【发布时间】:2021-02-23 10:34:54
【问题描述】:

我在一个文件夹中有一堆 .txt 文件。文本文件看起来像

0 45 67 78 56
1 56 45 35 45
5 56 66 34 21

我只想要每行的第一个字符(例如,我想要015 并将它们存储在像[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引用的那个
  • 我明白,但我该如何解决这个问题?
  • 顺便说一句,几乎没有充分的理由使用f.readlines,你可以直接使用for line in f: ...,因为文件对象已经是文件中行的迭代器。
  • ...创建一个新列表,所以就在for filename in glob(): ...下面做l = []
  • 这是学校的问题吗? :) 完全相同的问题:stackoverflow.com/questions/66328315/…

标签: python list file dictionary


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-01
    • 2019-05-04
    • 2019-07-03
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 2022-01-11
    相关资源
    最近更新 更多