很多情況下我們會從 Mongo
或者 MySQL
數(shù)據(jù)庫中導(dǎo)出數(shù)據(jù)為 csv
格式的數(shù)據(jù)文件煌寇,就行下面這樣
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
讀取數(shù)據(jù)
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()
函數(shù)會得到文件的第一行內(nèi)容涕滋,headers
和row
返回的都是列表類型的數(shù)據(jù)
輸出內(nèi)容:
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
假如你讀入數(shù)據(jù)后不是想展示的,而是用這些數(shù)據(jù)中的某個字段的值,那么可以使用對應(yīng)的索引來取值姐叁,但是我建議你用命名元組來包裝一下這些數(shù)據(jù)桑谍。
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)
輸出內(nèi)容
mysql-master
mysql-salve
mysql-salve
mycat
修改 csv 文件
假設(shè)延柠,我把剛才的文件內(nèi)修改一下,在最后添加一個字段 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)
# 寫數(shù)據(jù)
csv_wf.writerows(rows)
# 刪除原來的文件
os.remove('example.csv')
# 把含有新數(shù)據(jù)的文件名改為原來的文件名,實現(xiàn)修改文件
os.rename('.example.csv', 'example.csv')
寫入的數(shù)據(jù)源是列表字典
假如要寫入到數(shù)據(jù)是一個列表增热,列表中是字典整以,每個字典是一行數(shù)據(jù)
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)