首页 > 解决方案 > 在两个目录中搜索 excel 文件并创建路径

问题描述

我最近一周发布了一个类似的问题,关于搜索子目录以查找特定的 excel 文件。但是这一次,我需要在两个目录之一中找到一个特定文件,并根据该文件是位于一个文件夹中还是另一个文件夹中给出路径。

这是我到目前为止的代码。我拥有的工作计算机在 Python 2.7.18 上运行 - 没有错误但是当我将 df 打印为 excel 文件时,输出路径中没有显示任何内容

ExcelFilePath = sys.argv[1]
OutputFilePath = sys.argv[2]
    # path of excel directory and use glob glob to get all the DigSym files 
    for (root, subdirs, files) in os.walk(ExcelFilePath):
        for f in files:
            if '/**/Score_Green_*' in f and '.xlsx' in f:
                ScoreGreen_Files =  os.path.join(root, f)

                for f in ScoreGreen_Files:

                    df1 = pd.read_excel(f)
                    df1.to_excel(OutputFilePath)

标签: pythonexcelpandasio

解决方案


OutputFilePath是您要传入的参数。除非您将一个作为命令行参数传入,否则它不会有值。

如果要返回路径,则需要返回的变量是ScoreGreen_Files. 您也不需要遍历, ScoreGreen_Files因为它应该只是您要查找的文件。

ExcelFilePath = sys.argv[1]
OutputFilePath = sys.argv[2]
# path of excel directory and use glob glob to get all the DigSym files 
for (root, subdirs, files) in os.walk(ExcelFilePath):
    for f in files:
        if '/**/Score_Green_*' in f and '.xlsx' in f:  # f is a single file
            ScoreGreen_File = os.path.join(root, f)
            df1 = pd.read_excel(ScoreGreen_File)
            df1.to_excel(OutputFilePath)

推荐阅读