![](/img/trans.png)
[英]How to loop through each file in a folder, do some action to the file and save output to a file in another folder Python
[英]Python: Loop through a folder and save data from first tab of each file and save to new file on separate tabs
我正在嘗試遍歷特定文件夾中的 8 個文件,並從每個文件的第一個選項卡中的特定列中獲取數據。 然后,我想將數據粘貼到一個新的合並文件中,每個數據框都位於各自單獨的選項卡上。 這是我目前所擁有的......
我的問題:
import pandas as pd
import os
import glob
os.chdir(file path)
FileList = glob.glob('*.xlsx')
data = {}
for file in FileList:
df = pd.read_excel(file, 0, header=9)
df = df[['Project Code', 'Project', 'Location', 'Opening Balance Dollars', 'Accrued This Year Dollars',
'Opening Balance + Accrued Dollars', 'Taken Dollars', 'Closing Dollars']]
data[file] = df
要保存到 excel,您需要安裝openpyxl 。 然后我將 append 每個 df 放到一個列表中:
Filelist = glob.glob(r"path\*.xlsx")
list_df = []
for file in Filelist:
list_df.append(pd.read_excel(file))
# the names for each sheet in the consolidated file
names = ['sh1','sh2']
writer=pd.ExcelWriter(r"path\out.xlsx")
for i, df in enumerate(list_df):
df.to_excel(writer,sheet_name="{0}".format(names[i]),index = False)
writer.save()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.