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 文件的条目以及它们所在的目录。
解决方案
你不应该直接弄乱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 ... :
)已经在后台为您执行了该操作。
推荐阅读
- java - 如何调用包含在 Android 活动中的方法?
- python - 使用 pd.ExcelWriter 将许多数据帧写入单个 Excel 工作簿以进行 VBA 操作
- javascript - 反应原生相机 - 默认预览似乎在 IOS 上缩放
- javascript - 不发送推送通知
- javascript - Javascript,两个 async/await 和 promise func,但一个正在工作,另一个不工作
- android - Android Dokka - Only generate docs for my code and skip everything else
- android - Retrofit2 调用 viewpager
- javascript - PWA 的多个清单
- visual-studio - Xamarin.Android: 包 XX 与 monoandroid81 不兼容 (MonoAndroid,Version=v8.1)
- kotlin - Getting RuntimeException for kotlin code