【问题标题】:merge excel files with dynamic names合并具有动态名称的excel文件
【发布时间】:2021-07-21 17:44:57
【问题描述】:

我有一个需要每周自动刷新的 Excel 文件。它必须由其他 Excel 文件扩展。问题是这些文件每次都有不同的名称。 所以在我看来我不能使用这样的代码:

import pandas as pd 
NG = 'NG.xlsx'
df = pd.read_excel(NG)

因为在这种情况下,文件名并不总是“NG”。 你有什么想法吗?

最好的问候

【问题讨论】:

  • 这些文件是否都交付在同一个文件夹中?并且,您希望将新文件的内容连接到现有的 df 吗?
  • 感谢您的回答!是的,它们都在同一个文件夹中。是的,应该更新现有的 Excel 文件。

标签: python excel pandas concatenation


【解决方案1】:

您可以通过这样做读取文件夹中的所有文件,因为它允许您忽略名称更改:

import sys
import csv
import glob
import pandas as pd

# get data file names
path = r"C:\.......\folder_with_excel"
filenames = glob.glob(path + "/*.xlsx")

DF = []

for df in dfs: 
    xl_file = pd.ExcelFile(filenames)
    df=xl_file.parse('Sheet1')
    DF.concat(df, ignore_index=True)

或者:

import os
import pandas as pd

path = os.getcwd()
files = os.listdir(path)   # list all the files in you directory

files_xls = [f for f in files if f[-3:] == 'xlsx']  # make a list of the xlsx 

df = pd.DataFrame()

for f in files_xls:
    info = pd.read_excel(f, '<sheet name>')  # remove <sheet name if you don't need it
    df = df.append(info)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 2013-09-09
    • 2018-09-24
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 2019-07-13
    相关资源
    最近更新 更多