How can Python output the print content to a file?

In Python, you can use the file parameter of the print function to output printed content to a file. Here is an example:

# 打开文件
file = open("output.txt", "w")

# 将打印内容输出到文件中
print("Hello, World!", file=file)

# 关闭文件
file.close()

Firstly, use the open function to open a file, where the first parameter is the file path and the second parameter is the file opening mode. “w” indicates opening the file in write mode, creating a new file if it does not exist and clearing the contents if it already exists.

Then, use the print function to output the content to a file, with the file parameter specified as the file object that has already been opened.

Finally, use the close method to close the file, ensuring that the file resources are released after the operation is complete.

After running this code, the text “Hello, World!” will be written to a file named “output.txt”.

广告
Closing in 10 seconds
bannerAds