csv file read and write

csv file reads:

1) read by the standard list:

import csv
with open('stock.csv','r') as fp:
    # reader是个迭代器
    reader = csv.reader(fp)
    next(reader)
    for i in reader:
        # print(i)
        name = i[3]
        volumn = i[-1]
        print({'name':name,'volumn':volumn})

  The direct use of open () function to open csv file. Use csv.reader () method, wherein the parameter is a pointer. Since there is the csv file header, use may be used next () function skip the first set of data, i.e. the header data. Then obtain the desired data directly through the index list.

 

2) by acquiring key:

import csv
with open('stock.csv','r') as fp:
    reader = csv.DictReader(fp)
    for i in reader:
        value = {"name":i['secShortName'],"volumn":i['turnoverVol']}
        print(value)

   Use DictReader create reader objects that do not contain data header row, but not the same reader iterator created with the reader, traversing the iterator, is a return to the dictionary, not a list.

 

csv file is written:

1) using a writer to create objects, writerow (s) writes:

import csv
headers = ['username','age','height']
value = [
    ('张三',18,180),
    ('李四',19,175),
    ('王五',20,170)
]
with open("classroom.csv",'w',encoding='utf-8',newline='') as fp:
    writer = csv.writer(fp)
    writer.writerow(headers)
    writer.writerows(value)

  Write data to a csv file, you need to create a writer object before you can use writerow writes a line, and writerows is all written. Wherein the default newline = '\ n' will wrap i.e. writes a line, it is necessary to change the null data are stored in the list.

 

2) Use DictWriter create objects, writerow (s) writes:

import csv
headers = ['name','age','height']
value = [
    {'name':'张三','age':18,'height':180},
    {'name':'李四','age':19,'height':175},
    {'name':'王五','age':20,'height':170}
]
with open("classroom1.csv",'w',encoding='utf-8',newline='') as fp: #默认newline='\n'
    writer = csv.DictWriter(fp,headers)
    writer.writeheader()
    writer.writerows(value)

  When the data is located in a dictionary may be used DictWriter create writer objects, which need to pass two parameters, a pointer to a first, a second header information. When the object is created with DictWriter, also you need to perform the write header writeHeader () operation.

 

Guess you like

Origin www.cnblogs.com/zyde-2893/p/11257211.html