python合并多個excel文件的示例
工作中經常遇到要將十幾個Excel(不管是xls、或者是CSV)合并到同一個文件中去,手工一個一個復制是不可能的,此時就輪到Python出馬了
主要是利用for循環,讀取每一個文件,作為df,然后再通過list的append加在一起,然后再通過pd.concat拼接起來,最后將文件讀到CSV中去
import osimport pandas as pdimport numpy as npdir = 'D:merge'#設置工作路徑#新建列表,存放文件名(可以忽略,但是為了做的過程能心里有數,先放上)filename_excel = []#新建列表,存放每個文件數據框(每一個excel讀取后存放在數據框)frames = []for root, dirs, files in os.walk(dir): for file in files: #print(os.path.join(root,file)) filename_excel.append(os.path.join(root,file)) df = pd.read_excel(os.path.join(root,file)) #excel轉換成DataFrame frames.append(df)#打印文件名print(filename_excel) #合并所有數據result = pd.concat(frames) #查看合并后的數據result.head()result.shaperesult.to_csv(’D:mergea12.csv’,sep=’,’,index = False)#保存合并的數據到電腦D盤的merge文件夾中,并把合并后的文件命名為a12.csv
以上就是python合并多個excel文件的示例的詳細內容,更多關于python合并excel文件的資料請關注好吧啦網其它相關文章!
相關文章: