【问题标题】:Can't Glob Several File Types不能 Glob 几种文件类型
【发布时间】:2018-12-15 11:25:38
【问题描述】:

我已经对此问题进行了一段时间的研究和测试,但似乎无法让它发挥作用。

user_path

由用户提供,它包含 .xlsm、、xlsb 和 .xlsx 文件类型。我正在尝试捕获所有这些并将它们转换为 .csv。如果我替换扩展名,这将单独工作:

all_files = glob.glob(os.path.join(user_path, "*.xlsm")) #xlsb, xlsm

我尝试了以下两种方法,但都不起作用(win32com 只是告诉我 Excel 无法访问 out_folder。)

all_files = glob.glob(os.path.join(user_path, "*"))
all_files = glob.glob(user_path)

如何将这两种文件类型与 user_path 一起发送?

提前致谢。

【问题讨论】:

    标签: python-3.x operating-system glob win32com


    【解决方案1】:

    通过仅使用*glob 匹配给定文件夹下的所有文件和目录,包括您无权访问的文件和目录,在您的情况下是out_folder 目录,因此当您遍历文件名时,请确保它们是否以您正在寻找的文件扩展名之一结尾,然后再尝试打开它们。

    由于glob 不能同时测试多个文件扩展名,实际上最好使用os.listdir 并自己过滤多个文件扩展名。

    for filename in os.listdir(user_path):
        if any(map(filename.endswith, ('.xlsm', '.xlsb', '.xlsx'))):
            do_something(filename)
    

    或者,使用列表理解,

    all_files = [filename for filename in os.listdir(user_path) if any(map(filename.endswith, ('.xlsm', '.xlsb', '.xlsx')))]
    

    由 OP 编辑​​(实际代码)

        pathlib.Path(path + '\out_folder').mkdir(parents = True, exist_ok = True)
        newpath = os.path.join(path,'out_folder')
    #this is the line I can't seem to get to read both file types - it works as is.
        all_files_test = glob.glob(os.path.join(user_path, "*.xlsm")) #xlsb, xlsm
    
        for file in all_files_test:
            name1 = os.path.splitext(os.path.split(file)[1])[0]
    

    【讨论】:

    • 好的 - 谢谢,我想这就是我想要做的 - 我怎么能告诉它只查找/使用 .xlsb/.xlsm 而不是使用通配符?
    • 我已经用我推荐的解决方案更新了我的答案。
    • 好的,很酷,谢谢 - 看起来它会做到的 - 我想我刚刚挂在 glob/单班轮上 - 会试一试 - 谢谢!
    • 我看到了你的代码。如果您只是插入我的代码而不对现有代码进行任何更改,那么它肯定不会起作用,因为您遍历 all_files_test 的以下循环需要完整的路径名,而 os.listdir 只返回文件名,没有目录名.您只需将os.listdir 的输出与您的基本目录连接起来,例如all_files_test = [os.path.join(user_path, filename) for filename in os.listdir(user_path) if any(map(filename.endswith, ('.xlsm', '.xlsb', '.xlsx')))].
    • 非常感谢 - 我确实尝试过调整它,当然没有成功。我会试一试,非常感谢您的宝贵时间。
    猜你喜欢
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 2016-06-09
    • 2023-04-06
    • 2014-10-05
    相关资源
    最近更新 更多