简体   繁体   English

Python:如何将打印输出重定向到 txt 文件?

[英]Python: How to redirect print output to txt file?

I have Print function which looks like this: print(*hint_y, sep='\\n') (hint_y is nested list), which output looks like this:我有打印函数,它看起来像这样: print(*hint_y, sep='\\n') (hint_y 是嵌套列表),其输出如下所示:

      1    
    1 1 1  
  4 1 1 1 4

How can i redirect this print to text file?如何将此打印重定向到文本文件?

You can do that by using providing file proxy in the file parameter of print function.您可以通过在打印功能的文件参数中使用提供文件代理来做到这一点。

For example,例如,

f = open('temp.txt' , 'w')
print('a' , file = f)
f.close()

Here,I redirected string 'a' in the file 'temp.txt'.在这里,我重定向了文件“temp.txt”中的字符串“a”。

Like Sanchit.Jain's answer, but uses a with statement to close the file automatically:像 Sanchit.Jain 的回答,但使用 with 语句自动关闭文件:

with open('temp.txt' , 'w') as f:
    print('a' , file=f)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM