简体   繁体   English

Python:循环浏览文件夹并从每个文件的第一个选项卡保存数据并在单独的选项卡上保存到新文件

[英]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:我的问题:

  1. How do I grab the data from the first tab of each file?如何从每个文件的第一个选项卡中获取数据?
  2. How do I then paste that data into each of their own tabs on a consolidated file?然后如何将这些数据粘贴到合并文件上的每个选项卡中?
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.

相关问题 如何遍历文件夹中的每个文件,对文件进行一些操作以及将输出保存到另一个文件夹中的文件Python - 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将每个循环保存到新文件 - How to save each loop to a new file with python 如何将python函数的每个循环保存到单独的文件? - How to save each loop of a python function to a separate file? python通过扩展名分隔文件并相应地保存到文件夹中 - python separate file by extension and save into folder accordingly 如何将每个文件的标记化结果保存在新的单独的文本文件中? - How to save tokenization result for each file in a new separate text file? 将文件中不同列的数据保存到Python 2.7中的变量中 - Save data from separate columns in a file into a variable in Python 2.7 使用Python zip将数据保存在二进制文件的不同列中 - Use Python zip to save data in separate columns from a binary file 在循环 python 的每次迭代中保存 csv 文件 - Save csv file in each iteration of loop python 从文件中读取特定数据并将其保存在python中的新文件中 - To read the specific data from file and should save it new file in python Python-使用制表符分隔的单词将csv文件保存在单独的单元格中 - Python - save csv file with tab separated words in separate cell
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM