python csv模块读取/写入csv文件
文章目录
- 一、准备一个csv文件(test.csv)
- 二、读取csv文件
- 输出整个文件的数据
- 输出具体信息
- 输出所有的年龄
- 修改tom的年龄为20
- 增加一列信息
- 三、写入csv文件
- 四、完整代码
- 五、参考文章
一、准备一个csv文件(test.csv)
二、读取csv文件
输出整个文件的数据
import csv
with open('test.csv', 'r', encoding='utf-8') as f:
data = [row for row in csv.DictReader(f)]
print(data)
打印出来的值是一个列表里面嵌套了字典
输出具体信息
print(data[0]["age"]) #输出lili的年龄,0代表第一行
输出所有的年龄
with open('test.csv', 'r', encoding='utf-8') as f:
data = [row for row in csv.DictReader(f)]
for i in range(len(data)):
print(data[i]["age"])
修改tom的年龄为20
data[1]["age"] = 20
print(data)
增加一列信息
data[0]["phone"] = "123456"
data[1]["phone"] = "456789"
print(data)
三、写入csv文件
header = data[0].keys() # 获取表头
with open('test_output.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=header)
writer.writeheader() # 写入表头
writer.writerows(data) # 写入数据
四、完整代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import csv
with open('test.csv', 'r', encoding='utf-8') as f:
data = [row for row in csv.DictReader(f)]
data[1]["age"] = 20
data[0]["phone"] = "123456"
data[1]["phone"] = "456789"
header = data[0].keys() # 获取表头
with open('test_output.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=header)
writer.writeheader() # 写入表头
writer.writerows(data) # 写入数据
五、参考文章
Python 修改CSV文件实例详解