pyhon处理csv数据
时间: 2025-06-15 09:20:44 浏览: 10
在Python中,CSV(Comma Separated Values,逗号分隔值)文件是一种常用的文本文件格式,用于存储表格数据。Python提供了一个内置模块`csv`,可以帮助我们轻松地读取、写入和操作CSV文件。
以下是使用`csv`模块处理CSV数据的一些基本步骤:
1. **导入模块**:
```python
import csv
```
2. **打开文件(读取)**:
```python
with open('example.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
```
这会逐行读取文件内容。
3. **写入文件(创建或追加)**:
```python
data_to_write = ['Name', 'Age', 'City']
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(data_to_write)
```
这里我们创建一个新的CSV文件并写入一行数据。
4. **处理表头和数据**:
```python
with open('example.csv', 'r') as file:
reader = csv.DictReader(file) # 如果数据有标题行,可以使用DictReader
for row in reader:
print(row['Name'])
```
`DictReader`将每一行转换成字典,方便按字段名访问数据。
5. **使用pandas库处理更复杂的数据结构**:
```python
import pandas as pd
df = pd.read_csv('example.csv')
df.head() # 显示前几行
df.to_csv('processed_data.csv', index=False) # 导出到新的CSV
```
`pandas`提供了更强大的数据分析和处理功能。
阅读全文
相关推荐














