[英]Python: Loop through a folder and save data from first tab of each file and save to new file on separate tabs
I am trying to loop through 8 files in a specific folder and grab the data from specific column in the first tab of each.我正在尝试遍历特定文件夹中的 8 个文件,并从每个文件的第一个选项卡中的特定列中获取数据。 Then, I want to paste the data into a new, consolidated file with each of the data frames on their own separate tab.
然后,我想将数据粘贴到一个新的合并文件中,每个数据框都位于各自单独的选项卡上。 This is what I have so far...
这是我目前所拥有的......
My questions:我的问题:
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
To save to excel you need to have openpyxl installed.要保存到 excel,您需要安装openpyxl 。 Then I would append each df to a list:
然后我将 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.