Python—将字典输出到外部文本文件时,只输出第一个键
我的问题: 我需要用Python将字典中的每一项输出到外部文本文件中。 例如:Python—将字典输出到外部文本文件时,只输出第一个键,python,file,python-3.x,dictionary,printing,Python,File,Python 3.x,Dictionary,Printing,我的问题: 我需要用Python将字典中的每一项输出到外部文本文件中。 例如: dict1 = {} gen1 = 1 aha = 2 dict1['Generation'] = gen1 dict1['Population'] = aha for key, value in sorted(dict1.items()): print(key,':',value, file = open('text.txt', 'w')) 在这个例子中,我在字典中有两个键,但是当我运行代
dict1 = {}
gen1 = 1
aha = 2
dict1['Generation'] = gen1
dict1['Population'] = aha
for key, value in sorted(dict1.items()):
print(key,':',value, file = open('text.txt', 'w'))
在这个例子中,我在字典中有两个键,但是当我运行代码并转到文件时,唯一一行只输出第一个键
如何将字典中的所有键打印到外部文件中
谢谢您应该使用模块将dict转储到文件中,而不是重新发明轮子:
import json
dict1 = {}
gen1 = 1
aha = 2
dict1['Generation'] = gen1
dict1['Population'] = aha
with open('text.txt', 'w') as dict_file:
json.dump(dict1, dict_file)
每次调用open('text.txt','w')
都会截断文件。这意味着,在写入第二项之前,文件将被清除,第一项将丢失
您应该只打开一次,并将其保存在变量中:
# not final solution yet!
f = open('text.txt', 'w')
for key, value in sorted(dict1.items()):
print(key, ':', value, file=f)
但是,在Python中,大多数情况下都应使用以确保文件正确关闭:
with open('text.txt', 'w') as f:
for key, value in sorted(dict1.items()):
print(key, ':', value, file=f)
在
for
循环的每次迭代中,您都要重新打开文件以进行写入(从而清除它)。使用
with open('text.txt', 'w') as out:
for key, value in sorted(dict1.items()):
print(key,':',value, file=out)
或者,只需将原始代码中的
open('text.txt','w')
更改为open('text.txt','a')
,即可打开文件进行追加。不过,这比只打开一次文件效率要低。@John\u Sm1没问题。请随意接受解决问题的答案之一。