【发布时间】:2020-08-27 16:10:55
【问题描述】:
Thie 是我的文本文件的一个示例:
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, 101, 102, 209]
这会导致函数 readFromFile() 抛出错误,因为文本文件不再是相同的格式。
文本文件的期望输出是这样的:
A, 100 101 102 209
【问题讨论】:
-
我认为 dict 不可能。
-
你不能。这是无效的语法,它只是其他地方 XY 问题的症状
-
你专注于错误的事情。电流输出没有问题。你用它做什么很可能是你的问题
-
也许你可以这样做
{'A': '100, 101, 102', 'B':' 103, 104'},但不能这样做{'A': 100, 101, 102, 'B': 103, 104} -
谢谢。我真正的问题是当我更新字典时尝试在原始文件上写。例如,我用 int 209 更新 A 的值。我希望能够在文本文件上写为
A, 100 101 102 209。此时,它将始终写为:A, [100, 101, 102, 209]
标签: python dictionary split file-handling strip