For 循环避免在字典中写入最后一个键



我有一本这样的字典,

 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中的密钥写入文档文件,这就是我尝试过的。

 for sam in sample1.keys():
    doc  = sam + '.doc'
    doc  = open(doc, 'w')
    doc.write("A: [n")

现在它为SAPLUF创建了两个文件,但只写入了SAP,其他文件为空。for 循环以某种方式避免在sample1中写入最后一个key。我不明白这里有什么问题。任何建议将不胜感激。

谢谢

我认为

这可能是Python不刷新流的情况。您可能应该在编写后关闭文件(或者更好的是,使用上下文管理器):

with open(doc, 'w') as my_file:
    my_file.write('whatever')
写入

文件后未关闭该文件。您可以显式关闭它,但仅使用with更容易,因为即使代码失败,也会关闭文件。

 for sam in sample1.keys():
    doc  = sam + '.doc'
    with output as open(doc, 'w'):
        output.write("A: [n")

在写入文件之前,您应该打开两个单独的文件。我的方法如下:

for sam in sample1.keys():
    with open(sam + '.doc', 'w') as sam_doc:
        sam_doc.write("A: [n")

解释

使用 with 语句打开文件会在更新后自动关闭该文件。

最新更新