码迷,mamicode.com
首页 > 编程语言 > 详细

python读写操作csv及excle文件

时间:2020-03-15 19:00:36      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:div   from   文件   alt   pen   creat   and   bar   img   

技术图片
 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文件

标签:div   from   文件   alt   pen   creat   and   bar   img   

原文地址:https://www.cnblogs.com/zhouhuayin/p/12499212.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
分享档案
周排行
mamicode.com排行更多图片
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!