Python读取文件
时间: 2024-03-06 17:44:49 浏览: 76
Python 读写文件的操作代码
Python提供了多种读取文件的方式,下面是其中几种常用的方法:
1. 使用`open()`函数打开文件,并使用`read()`方法读取文件内容:
```python
file = open("filename.txt", "r")
content = file.read()
file.close()
```
2. 使用`with`语句自动关闭文件:
```python
with open("filename.txt", "r") as file:
content = file.read()
```
3. 逐行读取文件内容:
```python
with open("filename.txt", "r") as file:
for line in file:
print(line)
```
4. 读取指定行数的文件内容:
```python
with open("filename.txt", "r") as file:
lines = file.readlines() # 将文件内容按行读取到一个列表中
for i in range(5): # 读取前5行
print(lines[i])
```
5. 使用`readline()`方法逐行读取文件内容:
```python
with open("filename.txt", "r") as file:
line = file.readline()
while line:
print(line)
line = file.readline()
```
阅读全文