在Python中读取数据通常有以下几种方法:
使用内置的`open()`函数
打开文件并读取内容。
```python
with open('file.txt', 'r') as file:
content = file.read()
print(content)
使用`csv`模块
读取CSV格式的文件。
```python
import csv
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
使用`json`模块
读取JSON格式的文件。
```python
import json
with open('data.json', 'r') as file:
data = json.load(file)
使用Pandas库
读取CSV、Excel等格式的文件。
```python
import pandas as pd
df = pd.read_csv('data.csv')
print(df)
使用`xlrd`库
读取Excel文件。
```python
import xlrd
workbook = xlrd.open_workbook('data.xlsx')
sheet = workbook.sheet_by_index(0)
for row_idx in range(sheet.nrows):
print(sheet.row_values(row_idx))
逐行读取文件
对于大型文件,逐行读取可以提高效率。
```python
with open('file.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line.strip())
选择哪种方法取决于你要读取的数据类型和文件格式。使用`with`语句可以确保文件在读取后正确关闭