import csv
villains =
[
-
['Doctor',
'No'],
-
['Rosa',
'Klebb'],
-
['Mister',
'Big'],
-
['Auric',
'Goldfinger'],
-
['Ernst',
'Blofeld'],
-
]
with open('villains',
'wt')
as fout:
# 一个上下文管理器
csvout = csv.writer(fout)
csvout.writerows(villains)
#读取cvs
with open('villains',
'rt')
as fin:
# 一个上下文管理器
cin = csv.reader(fin)
villains =
[row for row in cin]
# 使用列表推导式
print(villains)
#读取成字典方式
with open('villains',
'rt')
as fin:
cin = csv.DictReader(fin, fieldnames=['first',
'last'])
villains =
[row for row in cin]
#将字典写入成标题在上面的方式
villains =
[
-
{'first':
'Doctor',
'last':
'No'},
-
{'first':
'Rosa',
'last':
'Klebb'},
-
{'first':
'Mister',
'last':
'Big'},
-
{'first':
'Auric',
'last':
'Goldfinger'},
-
{'first':
'Ernst',
'last':
'Blofeld'},
-
]
with open('villains',
'wt')
as fout:
cout = csv.DictWriter(fout,
['first',
'last'])
cout.writeheader()
cout.writerows(villains)
with open('villains',
'rt')
as fin:
#重头读取文件
cin = csv.DictReader(fin)
villains =
[row for row in cin]
Python格式处理--cvs表格
2021-06-18 18:09:01
浏览数 (1)