不能全局处理多种文件类型

Can't Glob Several File Types

我已经对这个问题进行了一段时间的研究和测试,但似乎无法正常工作。

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 一起发送?

提前致谢。

通过仅使用 *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]