Python文件如何读取文件
时间: 2023-11-05 18:10:39 浏览: 118
Python文件(TXT、csv、图片、音频、视频等)读写
Python提供了多种读取文件的方式,常见的有以下几种:
1. 使用`open()`函数打开文件并读取内容:
```python
with open('file.txt', 'r') as f:
content = f.read()
print(content)
```
2. 逐行读取文件内容:
```python
with open('file.txt', 'r') as f:
for line in f:
print(line.strip())
```
3. 读取指定行数的内容:
```python
with open('file.txt', 'r') as f:
lines = f.readlines()
for i in range(5):
print(lines[i])
```
4. 使用`csv`模块读取CSV文件:
```python
import csv
with open('file.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)
```
5. 使用`pandas`模块读取Excel文件:
```python
import pandas as pd
df = pd.read_excel('file.xlsx')
print(df)
```
阅读全文