python读取txt文件的数据
时间: 2023-11-30 08:02:31 浏览: 87
以下是Python读取txt文件数据的方法:
1.使用open()函数打开txt文件,使用read()函数读取文件内容并存储在变量中,最后关闭文件。
```python
file = open('example.txt', 'r')
content = file.read()
file.close()
print(content)
```
2.使用with语句打开txt文件,使用read()函数读取文件内容并存储在变量中,with语句会自动关闭文件。
```python
with open('example.txt', 'r') as file:
content = file.read()
print(content)
```
3.使用readlines()函数逐行读取txt文件内容并存储在列表中。
```python
with open('example.txt', 'r') as file:
content = file.readlines()
print(content)
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)