美文网首页
常用Python 读写excel、csv文件的操作办法

常用Python 读写excel、csv文件的操作办法

作者: 早鸟有饭吃 | 来源:发表于2020-05-26 09:50 被阅读0次

1、excel 写入

#excel 写入
import xlwt

myWorkbook = xlwt.Workbook()
mySheet = myWorkbook.add_sheet('Record_List') # 添加活页博
#数据写入,写入标题
mySheet.write(0, 0, "机器人语音测试反馈记录表") 

#数据循环写入
for i,contents in enumerate(content_list_all): #content_list_all为需写入的数组数据
    for j,content in enumerate(contents):
        mySheet.write(i+1,j,content)

myWorkbook.save('Debug' + '.xls') #保存excle数据表。

2、excel读取

#excel读取
import xlrd

data = xlrd.open_workbook('Debug.xls')#打开需要读取的excel表
table = data.sheets()[0] #提取第0个活页博,即excel中首个活页博
#取出数据
col_data = table.col_values(4) #取出第4列的数据,生成数组。
row_data =table.row_values(12) #取出第12行的数据,生成数组。
#获取行数和列数
nrows = table.nrows
ncols = table.ncols
#循环提取行列表数据
for i in range(nrows):
    print(table.row_values(i))
#提取单元格
cell1 = table.cell(0,0).value
cell2 = table.cell(3,3).value
#使用行列索引
cell_3 = table.row(0)[0].value
cell_4 = table.col(1)[0].value

3、写入csv

#写入csv
import csv

with open('records.csv','a',newline='') as code:
        m = csv.writer(code,dialect='excel')
        if head !=[]:
            m.writerow(head) #head 为标题栏信息,为数组。
            head = []
        m.writerow(the_content) #写入数据

4、读取csv

#读取csv
import csv

with open('records.csv', 'r') as f:
    content = csv.reader(f) #读取csv数据
    for row in content: #打印数据
        print(row)

相关文章

网友评论

      本文标题:常用Python 读写excel、csv文件的操作办法

      本文链接:https://www.haomeiwen.com/subject/nafmahtx.html