python打印到txt文件
时间: 2023-08-17 18:08:12 浏览: 49
可以使用Python的内置函数open()来读取一个txt文件,并使用print()函数打印文件内容。具体代码如下:
```
# 打开文件
file = open('example.txt', 'r')
# 读取文件内容
content = file.read()
# 打印文件内容
print(content)
# 关闭文件
file.close()
```
其中,'example.txt'是要读取的文件名,'r'表示以只读模式打开文件。读取文件内容后,将其存储在变量content中,并使用print()函数打印出来。最后,使用close()函数关闭文件。
相关问题
python打印txt文件的行数
可以使用以下代码来打印txt文件的行数:
```python
with open("file.txt", "r") as file:
lines = file.readlines()
print(len(lines))
```
这个代码将打开名为 "file.txt" 的文件,读取所有行并将其存储在一个列表中。然后,使用 `len()` 函数来获取列表的长度,即文件的总行数,并打印出来。
python将print打印保存到txt文件
可以使用Python中的文件操作来将print打印保存到txt文件中,具体步骤如下:
1. 打开文件:使用Python中的open()函数来打开一个文件,需要指定文件名和打开方式,例如:
```
f = open('output.txt', 'w')
```
其中,'output.txt'是文件名,'w'表示打开方式为写入(write)。
2. 将print输出保存到文件中:在程序中使用print函数打印需要保存的内容,然后使用Python中的重定向符号(>)来将输出重定向到文件中,例如:
```
print('Hello, world!', file=f)
```
其中,file=f表示将输出保存到文件对象f所代表的文件中。
3. 关闭文件:在程序结束时需要关闭文件,以便保存所有的输出内容,例如:
```
f.close()
```
完整的代码如下:
```
f = open('output.txt', 'w')
print('Hello, world!', file=f)
f.close()
```
这样就可以将print输出保存到txt文件中了。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)