我有这样一本字典,
print(sample_dict)
dict_items([('SAP', ['SAP_MM_1.gz', 'SAP_MM_2.gz']), ('LUF',['LUF_1.gz', 'LUF_2.gz'])])
sample1 = {x:[sample_dict[x][0]] for x in sample_dict}
print(sample1)
dict_items {'SAP': ['SAP_MM_1.gz'],
'LUF': ['LUF_1.gz']} 现在,我需要将上述sample1中的键作为doc文件写入,这就是我尝试过的。
for sam in sample1.keys():
doc = sam + '.doc'
doc = open(doc, 'w')
doc.write("A: [\n")现在,它为SAP和LUF创建了两个文件,但只有SAP被写入,其他文件为空。For循环在某种程度上避免在sample1中写入最后一个sample1。我不明白这是怎么回事。如有任何建议,将不胜感激。
谢谢
发布于 2019-01-31 10:52:13
我认为这可能是Python不冲流的情况。您可能应该在编写完文件后关闭该文件(或者更好地使用上下文管理器):
with open(doc, 'w') as my_file:
my_file.write('whatever')发布于 2019-01-31 10:53:42
您在写完文件后,不会关闭它。您可以显式地关闭它,但是使用with就更容易了,因为即使代码失败,它也会关闭文件。
for sam in sample1.keys():
doc = sam + '.doc'
with output as open(doc, 'w'):
output.write("A: [\n")发布于 2019-01-31 10:53:46
在写入文件之前,您应该打开两个单独的文件。我的方法如下:
for sam in sample1.keys():
with open(sam + '.doc', 'w') as sam_doc:
sam_doc.write("A: [\n")解释
使用with语句打开文件,在更新后自动关闭该文件。
https://stackoverflow.com/questions/54458830
复制相似问题