用Python实现CSV文件的创建和读写操作
时间: 2024-05-08 21:17:28 浏览: 11
创建CSV文件:
```python
import csv
# 创建CSV文件
with open('example.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'Gender']) # 写入表头
writer.writerow(['Tom', '18', 'Male']) # 写入数据
writer.writerow(['Lucy', '20', 'Female'])
```
读取CSV文件:
```python
import csv
# 读取CSV文件
with open('example.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
```
输出结果:
```
['Name', 'Age', 'Gender']
['Tom', '18', 'Male']
['Lucy', '20', 'Female']
```
写入CSV文件:
```python
import csv
# 写入CSV文件
data = [['Name', 'Age', 'Gender'], ['Tom', '18', 'Male'], ['Lucy', '20', 'Female']]
with open('example.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
```
读取CSV文件并转为字典:
```python
import csv
# 读取CSV文件并转为字典
with open('example.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
print(row['Name'], row['Age'], row['Gender'])
```
输出结果:
```
Tom 18 Male
Lucy 20 Female
```