首页 > 解决方案 > 将输出保存到文本文件

问题描述

提供的代码运行没有问题并创建文本文件,但它是空的。需要帮助以了解错误在哪里。如果我运行代码,它运行良好,但是一旦我尝试打印到文件,我就会得到空结果。


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 文件的条目以及它们所在的目录。

标签: python

解决方案


你不应该直接弄乱sys.stdout,因为这可能不会像你想要或期望的那样表现。

虽然您可以将 stdout 重定向到 print 语句中的文件,如下所示:

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

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

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 ... :)已经在后台为您执行了该操作。


推荐阅读