python读写操作csv及excle文件

Posted zhouhuayin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python读写操作csv及excle文件相关的知识,希望对你有一定的参考价值。

技术图片
 1 import csv
 2 
 3 #读取csv文件内容方法1
 4 csv_file = csv.reader(open(‘testdata.csv‘,‘r‘))
 5 next(csv_file, None)    #skip the headers
 6 for user in csv_file:
 7     print(user)
 8 
 9 #读取csv文件内容方法2
10 with open(‘testdata.csv‘, ‘r‘) as csv_file:
11     reader = csv.reader(csv_file)
12     next(csv_file, None)
13     for user in reader:
14         print(user)
15 
16 #从字典写入csv文件
17 dic = {‘fengju‘:25, ‘wuxia‘:26}
18 csv_file = open(‘testdata1.csv‘, ‘w‘, newline=‘‘)
19 writer = csv.writer(csv_file)
20 for key in dic:
21     writer.writerow([key, dic[key]])
22 csv_file.close()   #close CSV file
23 
24 csv_file1 = csv.reader(open(‘testdata1.csv‘,‘r‘))
25 for user in csv_file1:
26     print(user)
技术图片

2、python读写excle文件

 需要先用python pip命令安装xlrd , xlwt库~

技术图片
 1 import xlrd, xlwt   #xlwt只能写入xls文件
 2 
 3 #读取xlsx文件内容
 4 rows = []   #create an empty list to store rows
 5 book = xlrd.open_workbook(‘testdata.xlsx‘)  #open the Excel spreadsheet as workbook
 6 sheet = book.sheet_by_index(0)    #get the first sheet
 7 for user in range(1, sheet.nrows):  #iterate 1 to maxrows
 8     rows.append(list(sheet.row_values(user, 0, sheet.ncols)))  #iterate through the sheet and get data from rows in list
 9 print(rows)
10 
11 #写入xls文件
12 rows1 = [[‘Name‘, ‘Age‘],[‘fengju‘, ‘26‘],[‘wuxia‘, ‘25‘]]
13 book1 = xlwt.Workbook()   #create new book1 excle
14 sheet1 = book1.add_sheet(‘user‘)   #create new sheet
15 for i in range(0, 3):    
16     for j in range(0, len(rows1[i])):
17         sheet1.write(i, j, rows1[i][j])
18 book1.save(‘testdata1.xls‘)   #sava as testdata1.xls
技术图片

 

以上是关于python读写操作csv及excle文件的主要内容,如果未能解决你的问题,请参考以下文章

Python 之excle的读写

Python 对excle文件的读写数据处理小结

python读写excle

python对csv文件的读写操作

Python csv模块(读写文件)

python批量转换excl为csv