从文件中读取并添加到没有列表的字典中

问题描述

这是我的文本文件的一个示例:

A,100 101 102
B,103 104

我想从该文件中读取内容并创建字典。

这是我的代码:

def readFromFile():
d = {} # empty dictionary
with open('file.txt') as fr: #read from text file
    for line in fr.readlines(): # reading text file by line
        k,v = line.split(',') # splitting the line on text file by ',' to define the key and values
        v = v.split() # splitting the values in each key into a list
        for n in range( len(v) ): 
            v[n] = int(v[n]) # convert student id in list from str to int
        d[k] = v # build dictionary with keys and its values
return d

这是我的输出结果:

{'A': [100,101,102],'B': [103,104]}

我想使用此函数用int 209更新A的值:

def writeToFile(d):
with open('file.txt','w') as fw:
    for k,v in d.items():
        print(f'{k},{v}',file = fw)

我的文件将这样写:

A,[100,102,209]

这会导致函数readFromFile()抛出错误,因为文本文件不再具有相同的格式。

文本文件上的所需输出是这样的:

A,100 101 102 209

解决方法

问题是您没有以预期的格式写入文件。您需要使用与阅读时相同的格式。

def write_to_file(filename,d):
    with open(filename,'w') as fw:
        for k,v in d.items():
            line_data = ' '.join(map(str,v))
            print('{},{}'.format(k,line_data),file = fw)

您的readFromFile函数不会验证格式。因此,它当然会引发错误-仅捕获任何错误并将其报告为不良文件内容。

要在line_data上进行扩展,您希望将列表组合成单个字符串,并用空格分隔,因此在调用https://docs.python.org/3/library/stdtypes.html#str.join时将使用空格作为分隔符,并且将列表用作可迭代项。 >

但是,当然不能使用str.join来连接int。您需要将它们全部转换为str,因此您将map(str,v)作为可迭代的联接传递给它。内置函数https://docs.python.org/3/library/functions.html#map仅将一个函数(在这种情况下转换为str)应用于每个项目。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...