【问题标题】:error 'filenames' is not defined when consolidating multiple excel files合并多个 Excel 文件时未定义错误“文件名”
【发布时间】:2023-02-03 15:40:33
【问题描述】:

我的 Python 代码用于合并文件夹“excel_Report”中的多个 excel 文件 到 1 个主 excel 文件中。 我已经安装了所有库:pyodbc、pandas、plyer、glob2。 但是当我执行 python 时。有一个错误:

“NameError:名称‘文件名’未定义”

我不知道我的代码有什么问题。你能帮忙吗? 谢谢

import pyodbc
import pandas as pd
import os
from datetime import datetime
from plyer import notification
import glob



# getting excel files to be merged from the Desktop 
path = "T:\excel_Report"

# read all the files with extension .xlsx i.e. excel 
excel_files = glob.glob(path + "\*.xlsx")
print('File names:', filenames)

# empty data frame for the new output excel file with the merged excel files
outputxlsx = pd.DataFrame()


with xw.App(visible=False) as app:
    combined_wb = app.books.add()
    for excel_file in excel_files:
        wb = app.books.open(excel_file)
        for sheet in wb.sheets:
            sheet.copy(after=combined_wb.sheets[0])
        wb.close()
    #combined_wb.sheets[0].delete()
    combined_wb.save("T:/excel_Report/test.xlsx")
    combined_wb.close()


【问题讨论】:

  • 您应该查看引发错误的行。您正在尝试 print('File names:', filenames),但 filenames 未定义。

标签: python excel pandas


【解决方案1】:

你打错字了

您搜索路径中以 .xlsx 结尾的所有文件并将该变量命名为 excel_files

# read all the files with extension .xlsx i.e. excel 
excel_files = glob.glob(path + "*.xlsx")

但是您尝试访问一个名为filenames的变量

print('File names:', filenames)

您需要将其修复为

print('File names:', excel_files)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    相关资源
    最近更新 更多