[英]Python: How to redirect print output to txt file?
我有打印函数,它看起来像这样: print(*hint_y, sep='\\n')
(hint_y 是嵌套列表),其输出如下所示:
1
1 1 1
4 1 1 1 4
如何将此打印重定向到文本文件?
您可以通过在打印功能的文件参数中使用提供文件代理来做到这一点。
例如,
f = open('temp.txt' , 'w')
print('a' , file = f)
f.close()
在这里,我重定向了文件“temp.txt”中的字符串“a”。
像 Sanchit.Jain 的回答,但使用 with 语句自动关闭文件:
with open('temp.txt' , 'w') as f:
print('a' , file=f)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.