大數據處理經常要用到一堆表格,然后需要把數據導入一個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")
新聞熱點
疑難解答