python读取txt文件的方法
时间: 2024-03-28 08:33:26 浏览: 294
在Python中,可以使用以下几种方法来读取txt文件:
1. 使用`open()`函数打开文件,并使用`read()`方法读取文件内容:
```python
file = open('file.txt', 'r')
content = file.read()
file.close()
```
2. 使用`with open()`语句来自动关闭文件:
```python
with open('file.txt', 'r') as file:
content = file.read()
```
3. 逐行读取文件内容:
```python
with open('file.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line)
```
4. 使用`readline()`方法逐行读取文件内容:
```python
with open('file.txt', 'r') as file:
line = file.readline()
while line:
print(line)
line = file.readline()
```
阅读全文
相关推荐
















