Python print() 到文件示例

位置:首页>文章>详情   分类: Python教程 > 编程技术   阅读(375)   2024-05-15 11:00:22

Learn to use Python 打印() function to 将 Python 程序或 Python 脚本的打印输出重定向到文件.

1. 使用 文件 参数打印到文件

打印() 函数接受除要在标准输出(默认情况下为屏幕)上打印的对象之外的 5 个关键字参数。一个这样的关键字参数是文件

文件参数的默认值是系统标准输出,它在屏幕上打印输出。我们可以指定任何其他输出目标,它必须是一个带有写(字符串)方法的对象。

给定的 Python 程序以写入模式打开 表演.txt 并将测试 “你好,蚂蚁!” 写入文件。

sourceFile = open('demo.txt', 'w')
print('Hello, Python!', file = sourceFile)
sourceFile.close()

文件中的程序输出。

Hello, Python!

2. 将标准输出流重定向到文件

在某些情况下,可能不需要在所有打印() 语句中指定文件 参数。在这种情况下,我们可以暂时将所有标准输出流重定向到一个文件。

一旦所有需要的对象都写入文件中,我们就可以将标准输出重定向回标准输出

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.

3. 将脚本输出重定向到文件

另一种重定向输出的方法是在执行 Python 脚本时直接从命令行执行。我们可以使用>字符来重定向输出。

print('Hello, Python!')
$ python3 demo.py > demo.txt

脚本输出在文件中。

Hello, Python!

快乐学习!!

地址:https://www.cundage.com/article/python-print-to-file.html

相关阅读

Python example to 将字符串拆分为 列表 的标记 using the delimiters such as space, comma, 正则表达式, or multiple de...
Learn to use Python 打印() function to 将 Python 程序或 Python 脚本的打印输出重定向到文件. 1. 使用 文件 参数打印到文件 打印()
Python 继续 语句跳过 Loop 中当前迭代的循环内的其余代码,并将程序执行跳转到封闭循环的开头。 如果 继续 语句在嵌套循环内(一个循环在另一个循环内),则 继续 语句仅跳过封闭循环的当...
Python example to 将字符串拆分为 列表 的标记 using the delimiters such as space, comma, 正则表达式, or multiple de...
Learn to use Python 打印() function to 将 Python 程序或 Python 脚本的打印输出重定向到文件. 1. 使用 文件 参数打印到文件 打印() 函数接...
学习使用 Python httplib2 模块。 超文本传输协议 (HTTP) 是分布式协作超媒体信息系统的应用协议。 HTTP 是万维网数据通信的基础。 Python httplib2 模块提...
阅读、理解和练习这些 Python 示例,以更好地理解 Python 语言。这些简单的 Python 程序将帮助我们理解 Python 的基本编程概念。 此页面上的所有程序都经过测试,应该可以在...
阅读、理解和练习这些 Python 示例,以更好地理解 Python 语言。这些简单的 Python 程序将帮助我们理解 Python 的基本编程概念
1. Python 内置函数 蟒蛇绝对() 返回整数的绝对值,float;和复数的大小。 Python any() 函数 检查 Iterable 的至少一个元素是否为 True。 Python ...
Python pass 语句用于执行空语句。当我们不想在代码中的某个地方执行任何语句时,我们可以使用pass语句,但是Python要求我们指定一条语句以满足Syntax规则。 Python pa...