Python中如何将print函数输出重定向到文件

2023-03-25 00:00:00 函数 重定向 如何将

在Python中,我们可以使用文件对象来将 print() 函数的输出重定向到文件。我们可以使用内置的 open() 函数来打开一个文件,并且将它赋值给一个变量,然后将这个文件对象传递给 print() 函数的 file 参数。

以下是一个将 print() 函数输出重定向到文件的示例:

name = "pidancode.com"
age = 3

with open("output.txt", "w") as f:
    print("欢迎来到", name, "的世界,", age, "周岁啦!", file=f)

# 打开文件并读取内容
with open("output.txt", "r") as f:
    print(f.read())

输出:

欢迎来到 pidancode.com 的世界, 3 周岁啦!

在上述示例中,我们首先使用 with 语句打开一个名为 output.txt 的文件,并将其赋值给变量 f。我们在调用 print() 函数时,将 file 参数设置为变量 f,这样 print() 函数的输出就会被写入到 output.txt 文件中。

然后我们再次使用 with 语句打开文件并读取其中的内容,最后使用 print() 函数将读取的内容输出到屏幕上。

需要注意的是,在将文件对象传递给 print() 函数的 file 参数时,我们需要将文件对象放在括号中,即 file=(f),或者直接使用变量名,即 file=f。

相关文章