CSV data access

Read CSV data is very simple

Divided into two parts

read

Csv file can be used to read reader (f) under the csv module and DictReader (f)

mport csv

with open("text.csv","r") as f:
    f = csv.reader(f)
    for row in f:
        print(row)

Results are expressed as

['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
['AA', '39.48', '6/11/2007', '9:36am', '-0.18', '181800']
['AIG', '71.38 ' , ' 6/11/2007 ' , ' 9:36 am ' , ' -0.15 ' , ' 195500 ' ] 
[ ' AXP ' , ' 62.58 ' , ' 6/11/2007 ' , ' 9:36 am ' ' -0.46 ' , ' 935000 ' ] 
[ ' BA ' , ' 98.31 ' ,'6/11/2007', '9:36am', '+0.12', '104800']
['C', '53.08', '6/11/2007', '9:36am', '-0.25', '360900']
['CAT', '78.29', '6/11/2007', '9:36am ,''-0.23', '225400']

The use DictReader () to read a convenient way to file thing is that the index can be used to obtain information

import csv

with open("text.csv","r") as f:
    f = csv.DictReader(f)
    for row in f:
        print(row["Symbol"],row["Price"],row["Date"],row["Time"],row["Change"])

The results are expressed as the side

AA 39.48 -0.18 6/11/2007 9:36 am 
AT 71.38 6/11/2007 9:36 am -0.15 
AXP 62.58 6/11/2007 9:36 am -0.46 
BA 98.31 6/11/2007 9:36 am +0.12 
C 53.08 6/11/2007 9:36 am -0.25 
CAT 78.29 6/11/2007 9:36 am -0.23

 

Difference: personal preference, like with what kind, but they should be exposed to the reading mode selection based on different scenarios scene.

write

Write csv files when you need a little attention

First of all header information to be written csv file

Followed by the tail information is written

Two cases

One

headers = ['Symbol','Price','Date','Time','Change','Volume']
rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),
         ('AIG', 71.38, '6/11/2007', '9:36am', -0.15, 195500),
         ('AXP', 62.58, '6/11/2007', '9:36am', -0.46, 935000),
       ]

with open('stocks.csv','w') as f:
    f_csv = csv.writer(f)
    f_csv.writerow(headers)
    f_csv.writerows(rows)

当row中时字典时,就可以选择使用DictWriter写入数据

headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
rows = [{'Symbol':'AA', 'Price':39.48, 'Date':'6/11/2007',
        'Time':'9:36am', 'Change':-0.18, 'Volume':181800},
        {'Symbol':'AIG', 'Price': 71.38, 'Date':'6/11/2007',
        'Time':'9:36am', 'Change':-0.15, 'Volume': 195500},
        {'Symbol':'AXP', 'Price': 62.58, 'Date':'6/11/2007',
        'Time':'9:36am', 'Change':-0.46, 'Volume': 935000},
        ]

with open('stocks.csv','w') as f:
    f_csv = csv.DictWriter(f, headers)
    f_csv.writeheader()
    f_csv.writerows(rows)

Guess you like

Origin www.cnblogs.com/baihuatian/p/11597354.html