Learn to use Python 打印() function to 将 Python 程序或 Python 脚本的打印输出重定向到文件.
文件
参数打印到文件打印()
函数接受除要在标准输出(默认情况下为屏幕)上打印的对象之外的 5 个关键字参数。一个这样的关键字参数是文件。
文件
参数的默认值是系统标准输出
,它在屏幕上打印输出。我们可以指定任何其他输出目标,它必须是一个带有写(字符串)
方法的对象。
给定的 Python 程序以写入模式打开 表演.txt
并将测试 “你好,蚂蚁!”
写入文件。
sourceFile = open('demo.txt', 'w')
print('Hello, Python!', file = sourceFile)
sourceFile.close()
文件中的程序输出。
Hello, Python!
在某些情况下,可能不需要在所有打印()
语句中指定文件
参数。在这种情况下,我们可以暂时将所有标准输出流重定向到一个文件。
一旦所有需要的对象都写入文件中,我们就可以将标准输出重定向回标准输出
。
import sys
# Saving the reference of the standard output
original_stdout = sys.stdout
with open('demo.txt', 'w') as f:
sys.stdout = f
print('Hello, Python!')
print('This message will be written to a file.')
# Reset the standard output
sys.stdout = original_stdout
print('This message will be written to the screen.')
程序在设置标准输出到文件后输出到文件。
Hello, Python!
This message will be written to a file.
重置标准输出目标后,程序再次输出到控制台。
This message will be written to the screen.
另一种重定向输出的方法是在执行 Python 脚本时直接从命令行执行。我们可以使用>
字符来重定向输出。
print('Hello, Python!')
$ python3 demo.py > demo.txt
脚本输出在文件中。
Hello, Python!
快乐学习!!
地址:https://www.cundage.com/article/python-print-to-file.html