简介
csv即comma separate vaules,csv文件在日常中使用量很大,而python自带的csv模块可以与Excel进行良好的交互。
列表形式读写
无论是读还是写,都要先创建相应的读写对象
- 写
首先要创建 w r i t e r writer writer对象。写入主要有 w r i t e r o w writerow writerow和 w r i t e r o w s writerows writerows两种方法,分别可以写入一行和多行数据。
#把列表数据写入csv文件
#这里加个newline=‘’,否则会有空行
with open(filename,'w',newline='') as f:
myWriter = csv.writer(f)
myWriter.writerow(['head1','head2','head3'])
ls = [[1,2,3],[11,22,33],[111,222,333]]
myWriter.writerows(ls)
这里要特别注意打开文件时的 n e w l i n e = ′ ′ newline='' newline=′′
如果不加
['head1', 'head2', 'head3']
[]
['1', '2', '3']
[]
['11', '22', '33']
[]
['111', '222', '333']
[]
加了以后
['head1', 'head2', 'head3']
['1', '2', '3']
['11', '22', '33']
['111', '222', '333']
- 读
首先要创建 r e a d e r reader reader对象。
#以列表形式打印每行数据
with open(filename,'r') as f:
lines = csv.reader(f)
for line in lines:
print(line)
结果如下
['head1', 'head2', 'head3']
['1', '2', '3']
['11', '22', '33']
['111', '222', '333']
在实际应用时我们常常不需要表头值,可以用 _ _ n e x t _ _ ( ) \_\_next\_\_() __next__()方法跳过第一行,即
#以列表形式打印每行数据
with open(filename,'r') as f:
lines = csv.reader(f)
lines.__next__()
for line in lines:
print(line)
输出
['1', '2', '3']
['11', '22', '33']
['111', '222', '333']
字典形式读写
- 读
创建 D i c t R e a d e r DictReader DictReader对象,其余方法和列表读取类似
#将数据读取成字典的形式
with open(filename,'r') as f:
dicts = csv.DictReader(f)
for line in dicts:
print(type(line),line)
#如果想输出第一行
print(dicts.fieldnames)
结果如下
<class 'collections.OrderedDict'> OrderedDict([('head1', '1'), ('head2', '2'), ('head3', '3')])
<class 'collections.OrderedDict'> OrderedDict([('head1', '11'), ('head2', '22'), ('head3', '33')])
<class 'collections.OrderedDict'> OrderedDict([('head1', '111'), ('head2', '222'), ('head3', '333')])
['head1', 'head2', 'head3']
当然也可以转换为python的字典形式储存
#转换为python字典储存
result = {}
with open(filename,'r') as f:
dicts = csv.DictReader(f)
for item in dicts:
result[item['head1']]=item['head2']+'&'+item['head3']
print(result)
输出结果
{'1': '2&3', '11': '22&33', '111': '222&333'}
- 写
使用 D i c t W r i t e r DictWriter DictWriter方法,注意写的时候需要加上表头信息
#写入python字典
with open(filename,'w',newline='') as f:
fileheader = ['head1','head2']
dict_data = [{'head1':'1','head2':'2'},{'head1':'11','head2':'22'}]
dicts = csv.DictWriter(f,fileheader)
dicts.writeheader()
dicts.writerows(dict_data)