python中csv文件操作
时间: 2023-11-06 15:21:21 浏览: 114
在Python中,我们可以使用内置的csv模块来进行CSV文件的操作。下面是一些常见的CSV文件操作示例:
1. 读取CSV文件:
```python
import csv
with open('file.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
```
2. 写入CSV文件:
```python
import csv
data = [['Name', 'Age', 'City'],
['John', '25', 'New York'],
['Alice', '30', 'Chicago'],
['Bob', '35', 'Los Angeles']]
with open('file.csv', 'w') as file:
writer = csv.writer(file)
writer.writerows(data)
```
3. 使用字典方式读取CSV文件:
```python
import csv
with open('file.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
print(row['Name'], row['Age'], row['City'])
```
4. 使用字典方式写入CSV文件:
```python
import csv
data = [{'Name': 'John', 'Age': '25', 'City': 'New York'},
{'Name': 'Alice', 'Age': '30', 'City': 'Chicago'},
{'Name': 'Bob', 'Age': '35', 'City': 'Los Angeles'}]
fieldnames = ['Name', 'Age', 'City']
with open('file.csv', 'w') as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
```
这些是一些基本的CSV文件操作示例,你可以根据实际需求进行进一步的操作和处理。
阅读全文