Python讀寫操作csv和excle文件代碼實(shí)例
更新時(shí)間:2020年03月16日 11:54:09 作者:周華銀
這篇文章主要介紹了python讀寫操作csv和excle文件代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
1、python讀寫csv文件
import csv
#讀取csv文件內(nèi)容方法1
csv_file = csv.reader(open('testdata.csv','r'))
next(csv_file, None) #skip the headers
for user in csv_file:
print(user)
#讀取csv文件內(nèi)容方法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文件內(nèi)容
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, 0, 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
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python訪問mysql數(shù)據(jù)庫的實(shí)現(xiàn)方法(2則示例)
這篇文章主要介紹了python訪問mysql數(shù)據(jù)庫的實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了兩種Python操作MySQL數(shù)據(jù)庫的相關(guān)技巧,需要的朋友可以參考下2016-01-01
python使用pyhook監(jiān)控鍵盤并實(shí)現(xiàn)切換歌曲的功能
這篇文章主要介紹了python使用pyhook監(jiān)控鍵盤并實(shí)現(xiàn)切換歌曲的功能,非??犰诺囊粋€(gè)小程序,可以讓你在游戲時(shí)避免切出游戲直接換歌,需要的朋友可以參考下2014-07-07
使用Python制作一個(gè)極簡(jiǎn)四則運(yùn)算解釋器
這篇文章主要介紹了使用Python制作一個(gè)極簡(jiǎn)四則運(yùn)算解釋器,在使用工具之前,至少也要了解工具的作用,需要的朋友可以參考下2023-04-04
Python內(nèi)建類型list源碼學(xué)習(xí)
這篇文章主要為大家介紹了Python內(nèi)建類型list源碼學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
Python中的defaultdict與__missing__()使用介紹
下面這篇文章主要給大家介紹了關(guān)于Python中defaultdict使用的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-02-02

