Python讀寫操作csv和excle檔案程式碼例項
阿新 • • 發佈:2020-03-17
1、python讀寫csv檔案
import csv #讀取csv檔案內容方法1 csv_file = csv.reader(open('testdata.csv','r')) next(csv_file,None) #skip the headers for user in csv_file: print(user) #讀取csv檔案內容方法2 with open('testdata.csv','r') as csv_file: reader = csv.reader(csv_file) next(csv_file,None) for user in reader: print(user) #從字典寫入csv檔案 dic = {'fengju':25,'wuxia':26} csv_file = open('testdata1.csv','w',newline='') writer = csv.writer(csv_file) for key in dic: writer.writerow([key,dic[key]]) csv_file.close() #close CSV file csv_file1 = csv.reader(open('testdata1.csv','r')) for user in csv_file1: print(user)
2、python讀寫excle檔案
需要先用python pip命令安裝xlrd,xlwt庫~
import xlrd,xlwt #xlwt只能寫入xls檔案 #讀取xlsx檔案內容 rows = [] #create an empty list to store rows book = xlrd.open_workbook('testdata.xlsx') #open the Excel spreadsheet as workbook sheet = book.sheet_by_index(0) #get the first sheet for user in range(1,sheet.nrows): #iterate 1 to maxrows rows.append(list(sheet.row_values(user,sheet.ncols))) #iterate through the sheet and get data from rows in list print(rows) #寫入xls檔案 rows1 = [['Name','Age'],['fengju','26'],['wuxia','25']] book1 = xlwt.Workbook() #create new book1 excle sheet1 = book1.add_sheet('user') #create new sheet for i in range(0,3): for j in range(0,len(rows1[i])): sheet1.write(i,j,rows1[i][j]) book1.save('testdata1.xls') #sava as testdata1.xls
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。