高效辦公:Python處理excel檔案,擺脫無效辦公

一、Python處理excel檔案

1。 兩個標頭檔案

import xlrdimport xlwt

其中xlrd模組實現對excel檔案內容讀取,xlwt模組實現對excel檔案的寫入。

2。 讀取excel檔案

高效辦公:Python處理excel檔案,擺脫無效辦公

# 開啟excel檔案workBook = xlrd。open_workbook(excelPath)

# 獲取所有的sheet的名字allSheetNames = workBook。sheet_names()print(allSheetNames)

輸出:[‘Sheet1’, ‘Sheet2’]

# 按索引號獲取sheet的名字(string型別)sheet1Name = workBook。sheet_names()[1]print(sheet1Name)

輸出:Sheet2

# 指定選擇第二個sheetsheet1_content1 = workBook。sheet_by_index(1) # 獲取第二個sheet中的 某一列 資料,index為 列 的編號content = sheet1_content1。col_values(index)print(content )

輸出:[‘50_female_CNS’, 0。0001450627129261498, 0。00014610459059353443, 0。0001005863347657359, 6。582112999369104e-05, 0。00012061284774544405, ’ ‘, 0。00012075268247024065, 9。77776267815119e-05, 0。00012586155938565746, 0。0003279103274939261, 0。00022441965601437833 …]

# 指定選擇第二個sheetsheet1_content1 = workBook。sheet_by_index(1) # 獲取第二個sheet中的 某一行 資料,index為 行 的編號content = sheet1_content1。row_values(index)print(content)

輸出:[’’, 0。0001450627129261498, 0。00017014314076560212, 0。00018181811940739254, 0。0003775072437995825, 0。00042918333947459267, 0。0004889411346133797, 0。0001635510979069336, 0。00018714823789391146, 0。0002130216204564284, 0。0004294577819371397, 0。0004909460429236959, 0。0005394823288641913]

3。 寫入excel檔案

# 初始化寫入環境workbook = xlwt。Workbook(encoding=’utf-8‘)

# 建立一個 sheetworksheet = workbook。add_sheet(’sheet‘)# 呼叫 write 函式將內容寫入到excel中, 注意需按照 行 列 內容 的順序worksheet。write(0, 0, label=’car type‘)worksheet。write(0, 1, label=’50_female_CNS‘)worksheet。write(0, 2, label=’75_female_CNS‘)worksheet。write(0, 3, label=’95_female_CNS‘)# 儲存 excelworkbook。save(“你的路徑”)

二、Python處理txt檔案

1。 開啟txt檔案

#方法1,這種方式使用後需要關閉檔案f = open(“data。txt”,“r”)f。close()#方法2,使用檔案後自動關閉檔案with open(’data。txt‘,“r”) as f:

開啟檔案的模式主要有,r、w、a、r+、w+、a+

r:以讀方式開啟檔案,可讀取檔案資訊。

w:以寫方式開啟檔案,可向檔案寫入資訊。如檔案存在,則清空該檔案,再寫入新內容

a:以追加模式開啟檔案(即一開啟檔案,檔案指標自動移到檔案末尾),如果檔案不存在則建立

r+:以讀寫方式開啟檔案,可對檔案進行讀和寫操作。

w+:消除檔案內容,然後以讀寫方式開啟檔案。

a+:以讀寫方式開啟檔案,並把檔案指標移到檔案尾。

2。 讀取txt檔案

# 讀出檔案,如果有count,則讀出count個位元組,如果不設count則讀取整個檔案。f。read([count]) # 讀出一行資訊。 f。readline() # 讀出所有行,也就是讀出整個檔案的資訊。 f。readlines()

高效辦公:Python處理excel檔案,擺脫無效辦公

f = open(r“F:\test。txt”, “r”)print(f。read(5))f。close()

輸出:1 2 3

f = open(r“F:\test。txt”, “r”)print(f。readline())print(f。readline())f。close()

輸出:

1 2 3 4 5

6,7,8,9,10

f = open(r“F:\test。txt”, “r”)print(f。readlines())f。close()

輸出:[‘1 2 3 4 5\n’, ‘6,7,8,9,10\n’]

上述讀取的格式均為:

str 型別

3。 寫入txt檔案(需注意別清空了原來的內容)

首先指定待寫入的檔案,注意這裡是

‘w’

f = open(r’F:\test。txt‘,’w‘)f。write(’hello world!‘)f。close()

高效辦公:Python處理excel檔案,擺脫無效辦公

content = [’\nhello world1!‘,’\nhello world2!‘,’\nhello world3!\n‘]f = open(r’F:\test。txt‘,’w‘)f。writelines(content)f。close()

高效辦公:Python處理excel檔案,擺脫無效辦公