1. 程式人生 > >如何用python遍歷資料夾下的所有excel檔案

如何用python遍歷資料夾下的所有excel檔案

大資料處理經常要用到一堆表格,然後需要把資料匯入一個list中進行各種演算法分析,簡單講一下自己的做法:

1.如何讀取excel檔案

網上的版本很多,在xlrd模組基礎上,找到一些原始碼:

import  xdrlib ,sys
import xlrd
def open_excel(file="C:/Users/flyminer/Desktop/新建 Microsoft Excel 工作表.xlsx"):
        data = xlrd.open_workbook(file)
        return data
#根據索引獲取Excel表格中的資料   引數:file:Excel檔案路徑     colnameindex:表頭列名所在行的所以  ,by_index:表的索引
def excel_table_byindex(file="C:/Users/flyminer/Desktop/新建 Microsoft Excel 工作表.xlsx",colnameindex=0,by_index=0):
    data = open_excel(file)
    table = data.sheets()[by_index]
    nrows = table.nrows #行數
    ncols = table.ncols #列數
    colnames =  table.row_values(colnameindex) #某一行資料
    list =[]
    for rownum in range(1,nrows):
         row = table.row_values(rownum)
         if row:
             app = {}
             for i in range(len(colnames)):
                app[colnames[i]] = row[i]
             list.append(app)
    return list
#根據名稱獲取Excel表格中的資料   引數:file:Excel檔案路徑     colnameindex:表頭列名所在行的所以  ,by_name:Sheet1名稱
def excel_table_byname(file="C:/Users/flyminer/Desktop/新建 Microsoft Excel 工作表.xlsx",colnameindex=0,by_name=u'Sheet1'):
    data = open_excel(file)
    table = data.sheet_by_name(by_name)
    nrows = table.nrows #行數
    colnames =  table.row_values(colnameindex) #某一行資料
    list =[]
    for rownum in range(1,nrows):
         row = table.row_values(rownum)
         if row:
             app = {}
             for i in range(len(colnames)):
                app[colnames[i]] = row[i]
             list.append(app)
    return list

def main():
   tables = excel_table_byindex()
   for row in tables:
       print(row)
   tables = excel_table_byname()
   for row in tables:
       print(row)
if __name__=="__main__":
    main()
最後一句是重點,所以這裡也給程式碼人點個贊!

最後一句讓程式碼裡的函式都可以被複用,簡單地說:假設檔名是a,在程式中import a以後,就可以用a.excel_table_byname()和a.excel_table_byindex()這兩個超級好用的函數了。

2.然後是遍歷資料夾取得excel檔案以及路徑:,原創程式碼如下:

import os
import xlrd
import test_wy
xpath="E:/唐偉捷/電力/電力系統總資料夾/舟山電力"
xtype="xlsx"
typedata = []
name = []
raw_data=[]
file_path=[]
def collect_xls(list_collect,type1):
    #取得列表中所有的type檔案
    for each_element in list_collect:
        if isinstance(each_element,list):
            collect_xls(each_element,type1)
        elif each_element.endswith(type1):
              typedata.insert(0,each_element)
    return typedata
#讀取所有資料夾中的xls檔案
def read_xls(path,type2):
    #遍歷路徑資料夾
    for file in os.walk(path):
        for each_list in file[2]:
            file_path=file[0]+"/"+each_list
            #os.walk()函式返回三個引數:路徑,子資料夾,路徑下的檔案,利用字串拼接file[0]和file[2]得到檔案的路徑
            name.insert(0,file_path)
        all_xls = collect_xls(name, type2)
    #遍歷所有type檔案路徑並讀取資料
    for evey_name in all_xls:
        xls_data = xlrd.open_workbook(evey_name)
        for each_sheet in xls_data.sheets():
            sheet_data=test_wy.excel_table_byname(evey_name,0,each_sheet.name)
            #請參考讀取excel檔案的程式碼
            raw_data.insert(0, sheet_data)
            print(each_sheet.name,":Data has been done.")
    return raw_data
a=read_xls(xpath,xtype)
print("Victory")
歡迎各種不一樣的想法~~