python输出到文件
时间: 2023-08-31 17:10:40 浏览: 166
可以使用Python中的文件操作函数,将print输出的内容写入到txt文件中。具体步骤如下:
1. 打开txt文件,使用open函数,指定文件名和打开模式('w'表示写入模式)。
2. 使用print函数输出内容,将输出内容作为参数传递给文件对象的write方法,将内容写入到txt文件中。
3. 关闭文件,使用文件对象的close方法关闭文件。
示例代码如下:
```
# 打开txt文件
file = open('output.txt', 'w')
# 输出内容到txt文件
print('Hello, World!', file=file)
# 关闭文件
file.close()
```
执行以上代码后,会在当前目录下生成一个名为output.txt的文件,文件内容为'Hello, World!'。
阅读全文
相关推荐














