将输出保存到文本文件

时间:2019-05-19 15:35:33

标签: python

提供的代码可以正常运行并创建文本文件,但是它为空。需要帮助以了解错误在哪里。如果我运行该代码,它将运行良好,但是当我尝试打印到文件时,会得到空结果。


stdoutOrigin=sys.stdout 
sys.stdout = open("log.txt", "w+")

listOfFiles = os.listdir('s:\\')  
pattern = "*.txt"  
for entry in listOfFiles:  
    if fnmatch.fnmatch(entry, pattern):
            print (entry)

sys.stdout.close()
sys.stdout=stdoutOrigin

预期结果应该是一个文本文件,其中包含所有* .txt文件的条目以及它们所在的目录。

1 个答案:

答案 0 :(得分:1)

您应该不要直接与sys.stdout混为一谈,因为这可能不会像您希望的或期望的那样表现。

可以将stdout重定向到打印语句中的文件,如下所示:

output = open("log.txt", "w")
print("hello", file=output)
output.close()

您真正应该做的是利用Python的上下文管理器以一种更具可读性和可维护性的方式将数据写入文件:

listOfFiles = os.listdir('s:\\')
pattern = "*.txt"
with open("log.txt", "w") as f:
    for entry in listOfFiles:
        if fnmatch.fnmatch(entry, pattern):
            f.write(entry)

请注意,这里不需要调用f.close(),因为上下文管理器(行with ... as ... :)已经为您提供了帮助。

相关问题