Python的收集整理:csv模块, xlrd模块

csv模块

写入

import csv
address = '\test.csv'  #文件地址
#元素为字典:
#打开方式用'w',还可以添加参数encoding='utf8',参数newline=''可以避免空行                
with open(address,'w',newline='') as fout:
    cout = csv.DictWriter(fout,['Name','SumCount','DropCount','OutCount','InCount']) #[]list里的为CSV的表头名
    cout.writeheader()   #写入表头
    cout.writerows(data) #data是一个列表list,其中的元素是字典dict,注意字典的key要与前面表头名对应
    
#元素为列表:
#改为:
cout = csv.writer(fout)
cout.writerows(data)

读取

#读成列表:
with open(address,'r') as fin:
    cin = csv.reader(fin)
    out = [row for row in cin]
print(out)#是一个列表,每行也是个列表

#读成字典:
#原本没有表头:
with open(address,'r') as fin:
    cin = csv.DictReader(fin,filenames=['first','last'])
    out = [row for row in cin]
print(out)

#原本有表头:
with open(address,'r') as fin:
    cin = csv.DictReader(fin)
    out = [row for row in cin]
print(out)

xlrd模块

读取

import xlrd
address = 'test.xls'

def read_xls():
    outdata = []
    data = xlrd.open_workbook(address)
    table = data.sheets()[0]
    title = table.row_values(0)

    for row in range(2, table.nrows):
        rn = [i.strip() for i in table.row_values(row)]
        d = {k: v for k, v in zip(title, rn)}
        #print(d)
        outdata.append(d)
    return outdata

你可能感兴趣的:(Python的收集整理:csv模块, xlrd模块)