【问题标题】:How do I create a dictionary that has the filename as key and the first character of the lines( in the file ) as values?如何创建一个以文件名作为键、行的第一个字符(在文件中)作为值的字典?
【发布时间】:2021-02-23 06:44:12
【问题描述】:

所以我有一些包含数据/行的 txt 文件。例如,文件 Q127.txt 将包含:

    0 45 67 78 91
    0 56 78 89 01
    5 56 43 56 67

我只想读取文件中每一行的第一个字符。我通过以下方式实现的:

    file = open("Q127.txt","r")
    for line in file.readlines():
        print(line[0]) # just printing to show what i get

    output: 0
            0
            5

现在因为我有很多这样的 .txt 文件,我想从一个文件夹中读取它们,并将文件名(作为键)和行 [0] 值(作为值)存储在一个名为类的字典中。所以类应该是这样的

     classes={"Q127.txt": [0,0,5], "Q128.txt": [5,8,0,1,1,1,1],..........}

我如何实现这一目标? 编辑:这是我尝试过的,但我仍然没有得到想要的输出

    import os
    file = open("Q127.txt","r")
    classes={}
    l=[]
    for line in file.readlines():
        l.append(line[0])
        classes[file]=[l]
    classes # to see the output

    output:
    {<_io.TextIOWrapper 
    name='Q127.txt' mode='r' 
    encoding='cp1252'>: [['0','0']]}

【问题讨论】:

  • 您尝试过什么来实现上述行为,在实施您尝试的解决方案时有什么问题?
  • 嗨,我已经编辑了关于我尝试过的问题。
  • 请将类[file]=[l]移到for循环之外
  • 另外,您不能使用文件作为键,它具有文件对象而不仅仅是文件名。将其用作 classes_dict[file.name] = values
  • 您想将文件名(即字符串)设置为字典键。但是在classes[file]=[l] 行中,您将相应的文件对象设置为键。将其更改为 classes[file.name]=[l] 并将这条线移到循环之外,因为它在里面很简单

标签: python file dictionary


【解决方案1】:

有两种方法可以维护这本字典。

  1. 如果您想一次又一次地为每个文件运行此脚本。那么您需要创建字典并将其保存到数据库中。当你下次读取另一个文件时,你需要先从数据库中获取字典,更新它并保存回来。 或

  2. 您必须将其作为一个脚本运行(在一个脚本中读取所有文件),在 for 循环的开头和内部创建一个空字典,将值作为列表传递。即

    classess_dict = {}

    //在for循环中:

    classes_dict[文件名]=[值]

【讨论】:

  • 我试过这个,但我得到的输出和我有问题的一样
  • 检查您的问题的 cmets,您使用文件对象作为键。你需要改变它。
【解决方案2】:

您可以将文件存储在变量中,

file_list= ['test.txt'] # you can use the os.listdir() to obtain the list 
                           of  files and location
classes= {}
for i in file_list:
    content= open(i).readline()# reads only first line
    classes[i]= content.split(' ')[0]



【讨论】:

  • 我只想读取文件中所有行的第一个字符。不只是第一行
【解决方案3】:

第一个字符总是数字吗?然后您可以使用int(line[0]) 将第一个字符计算为数字,还可以访问file.name 成员以用作该行的字典键:

    import os
    file = open("Q127.txt","r")
    classes={}
    l=[]
    for line in file.readlines():
        l.append(int(line[0]))
    # move the classes dictionary assignment out of the for loop, l already a list, no need to put brackets around it
    classes[file.name]=l
    classes # to see the output

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    相关资源
    最近更新 更多