将输出保存到文本文件

2024-06-08 00:22:45 发布

您现在位置: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文件的条目以及它们所在的目录。你知道吗


Tags: 文件代码txt错误stdoutsysopenpattern
1条回答
网友
1楼 · 发布于 2024-06-08 00:22:45

你应该不要直接和sys.stdout乱搞,因为那样做很可能不会像你所希望的那样。你知道吗

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

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 ... :)已经在幕后为您做了这件事。你知道吗

相关问题 更多 >

    热门问题