Python讀寫操作csv和excle文件代碼實(shí)例
1、python讀寫csv文件
import csv#讀取csv文件內(nèi)容方法1csv_file = csv.reader(open(’testdata.csv’,’r’))next(csv_file, None) #skip the headersfor user in csv_file: print(user)#讀取csv文件內(nèi)容方法2with 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 filecsv_file1 = csv.reader(open(’testdata1.csv’,’r’))for user in csv_file1: print(user)
2、python讀寫excle文件
需要先用python pip命令安裝xlrd , xlwt庫(kù)~
import xlrd, xlwt #xlwt只能寫入xls文件#讀取xlsx文件內(nèi)容rows = [] #create an empty list to store rowsbook = xlrd.open_workbook(’testdata.xlsx’) #open the Excel spreadsheet as workbooksheet = book.sheet_by_index(0) #get the first sheetfor user in range(1, sheet.nrows): #iterate 1 to maxrows rows.append(list(sheet.row_values(user, 0, sheet.ncols))) #iterate through the sheet and get data from rows in listprint(rows)#寫入xls文件rows1 = [[’Name’, ’Age’],[’fengju’, ’26’],[’wuxia’, ’25’]]book1 = xlwt.Workbook() #create new book1 exclesheet1 = book1.add_sheet(’user’) #create new sheetfor 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
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Android如何加載Base64編碼格式圖片2. 詳解Android studio 動(dòng)態(tài)fragment的用法3. 解決Android studio xml界面無(wú)法預(yù)覽問(wèn)題4. 基于android studio的layout的xml文件的創(chuàng)建方式5. 圖文詳解vue中proto文件的函數(shù)調(diào)用6. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁(yè)效果(實(shí)例代碼)7. 什么是python的自省8. 使用Android studio查看Kotlin的字節(jié)碼教程9. Vuex localStorage的具體使用10. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)

網(wǎng)公網(wǎng)安備