所以,这是我的代码:
file = open("save_file.txt")
for each_line in file:
s = {}
(s['name'], s['race'], s['class'], s['FOR'], s['INT'], s['DES']) = each_line.split(";")
file.close()
print(s['name'])
print(s['race'])
print(s['class'])
print(s['FOR'])
print(s['INT'])
print(s['DES'])
print(s['name'])
save_file.txt
:
Nome: d;Raça: Humano;Classe: Mago;FOR: 5;INT: 7;DES: 5
Nome: g;Raça: umano;Classe: Mo;FOR: 56;INT: 47;DES: 85
当我启动程序时,程序只打印第二行。如何打印两条或更多条线?
答案 0 :(得分:1)
首先,您要为文件中的每一行创建一个新的空dict
,因此s
只能包含文件中最后一行的值。要存储多行的值,您需要在s
循环之外移动for
的初始化。
其次,如果您希望dict
中的每个键都包含多个字符串值,那么您需要将它们存储在list
或其他类型的序列中。我建议使用defaultdict
,这样您就可以使用空列表自动填充缺失的密钥:
from collections import defaultdict
# ...
# missing keys will be automatically populated with empty lists
s = defaultdict(list)
keys = ['name', 'race', 'class', 'FOR', 'INT', 'DES']
for each_line in file:
# in order to store multiple values under each key, append them to
# a list
for kk, vv in zip(keys, each_line.split(";")):
s[kk].append(vv)
# ...
答案 1 :(得分:0)
如果程序只是打印第二行,那将是因为您在循环的每次迭代中覆盖字典,然后仅在循环的最后一次迭代之后打印。尝试这样的事情:
file = open("save_file.txt")
for each_line in file:
s = {}
(s['name'], s['race'], s['class'], s['FOR'], s['INT'], s['DES']) = each_line.split(";")
print(s['name'])
print(s['race'])
print(s['class'])
print(s['FOR'])
print(s['INT'])
print(s['DES'])
print(s['name'])
file.close()