python 读写CSV数据

2022-05-22  本文已影响0人  孙广宁
6.1 使用csv模块来读写csv数据
~/ning-dashboard/tmp > cat test.csv                                                                                     2m 56s
symbol,price,date
"A",30.3,"6/11/2022"
"B",30.1,"5/11/2022"
一、读取CSV文件
>>> import csv
>>> with open("test.csv") as f:
...     f_csv = csv.reader(f)
...     headers = next(f_csv)
...     print(headers)
...     for r in f_csv:
...         print(r)
...
['symbol', 'price', 'date']
['A', '30.3', '6/11/2022']
['B', '30.1', '5/11/2022']
>>>
>>> import csv
>>> from collections import namedtuple
>>> with open("test.csv") as f:
...     f_csv = csv.reader(f)
...     headers = next(f_csv)
...     row = namedtuple('row',headers)
...     for r in f_csv:
...         rl = row(*r)
...         print(rl)
...
row(symbol='A', price='30.3', date='6/11/2022')
row(symbol='B', price='30.1', date='5/11/2022')
>>>
>>> rl.symbol
'B'
>>> rl.price
'30.1'
>>> rl.date
'5/11/2022'
>>>
>>> with open("test.csv") as f:
...     f_csv = csv.DictReader(f)
...     for row in f_csv:
...         print(row)
...
OrderedDict([('symbol', 'A'), ('price', '30.3'), ('date', '6/11/2022')])
OrderedDict([('symbol', 'B'), ('price', '30.1'), ('date', '5/11/2022')])
>>> row['symbol']
'B'
>>> row['price']
'30.1'
>>>

二、写入csv文件

>>> h = ["test","test2","test3"]
>>> d = [("1",2,3),("2",30,20)]
>>> with open("test1.csv",'w') as f:
...     f_csv = csv.writer(f)
...     f_csv.writerow(h)
...     f_csv.writerows(d)

~/ning-dashboard/tmp > cat test1.csv
test,test2,test3
1,2,3
2,30,20
>>> import csv
>>> d = [("1",2,3),("2",30,20)]
>>> h = ["test","test2","test3"]
>>> with open("test2.csv",'w') as f:
...     f_csv = csv.DictWriter(f,h)
...     f_csv.writeheader()
...     f_csv.writerows(d)
...
上一篇下一篇

猜你喜欢

热点阅读