Python3 操作 csv 数据文件
2018-11-23 本文已影响76人
运维开发_西瓜甜
很多情况下我们会从 Mongo
或者 MySQL
数据库中导出数据为 csv
格式的数据文件,就行下面这样
example.csv
Host,IP,Port,Status,Disk,Memory
"mysql-master","192.168.11.61",3306,"up",2048,32
"mysql-salve","192.168.11.62",3306,"up",3096,16
"mysql-salve","192.168.11.63",3306,"down",2048,16
"mycat","192.168.11.60",8066,"up",2048,16
读取数据
with open('example.csv') as f:
f_csv = csv.reader(f)
headers = next(f_csv)
print(*headers)
for row in f_csv:
print(*row)
f_csv
会是一个迭代器,使用next()
函数会得到文件的第一行内容,headers
和row
返回的都是列表类型的数据
输出内容:
Host IP Port Status Disk Memory
mysql-master 192.168.11.61 3306 up 2048 32
mysql-salve 192.168.11.62 3306 up 3096 16
mysql-salve 192.168.11.63 3306 down 2048 16
mycat 192.168.11.60 8066 up 2048 16
假如你读入数据后不是想展示的,而是用这些数据中的某个字段的值,那么可以使用对应的索引来取值,但是我建议你用命名元组来包装一下这些数据。
from collections import namedtuple
with open('example.csv') as f:
f_csv = csv.reader(f)
headings = next(f_csv)
Row = namedtuple('Row', headings)
for r in f_csv:
row = Row(*r)
print(row.Hose)
输出内容
mysql-master
mysql-salve
mysql-salve
mycat
修改 csv 文件
假设,我把刚才的文件内修改一下,在最后添加一个字段 Other
,之后再存入原来的文件,我可以这样做
import csv, os
with open('example.csv') as f, open('.example.csv', 'w', encoding='utf-8') as w_f:
csv_rf = csv.reader(f)
headers = next(csv_rf)
# 添加表头字段
headers.append('Other')
rows = []
for row in csv_rf:
# 为每行添加值
row.append("other")
# 把每一行添加到列表
rows.append(row)
# 把可写文件对象给到模块的写方法,返回一个 csv 的写对象
csv_wf = csv.writer(w_f)
# 写表头
csv_wf.writerow(headers)
# 写数据
csv_wf.writerows(rows)
# 删除原来的文件
os.remove('example.csv')
# 把含有新数据的文件名改为原来的文件名,实现修改文件
os.rename('.example.csv', 'example.csv')
写入的数据源是列表字典
假如要写入到数据是一个列表,列表中是字典,每个字典是一行数据
headers = ['Host', 'IP', 'Port', 'Status', 'Disk', 'Memory', 'Other']
rows = [
{'Host': 'mycat', 'IP': '192.168.11.60', 'Port': 8066, 'Status': 'up', 'Disk': '2048', 'Memory': '16', 'Other': 'other'},
{'Host': 'mycat', 'IP': '192.168.11.60', 'Port': 8066, 'Status': 'up', 'Disk': '2048', 'Memory': '16', 'Other': 'other'},
{'Host': 'mycat', 'IP': '192.168.11.60', 'Port': 8066, 'Status': 'up', 'Disk': '2048', 'Memory': '16', 'Other': 'other'},
{'Host': 'mycat', 'IP': '192.168.11.60', 'Port': 8066, 'Status': 'up', 'Disk': '2048', 'Memory': '16', 'Other': 'other'}
]
那你可以直接就行写入到一个文件中,无序多余的处理
with open('host_info.csv','w') as f:
f_csv = csv.DictWriter(f, headers)
f_csv.writeheader()
f_csv.writerows(rows)