python讀寫操作csv及excle文件


1、python讀寫csv文件

 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM