python中的glob函数,带有一个通配符

时间:2022-09-01 23:17:40

I have a problem with the glob.glob function in Python.

我在Python中的glob.glob函数有问题。

This line works perfectly for me getting all text files with the name 002 in the two subsequent folders of Models:

这行很适合我在模型的两个后续文件夹中获取名称为002的所有文本文件:

     All_txt    = glob.glob("C:\Users\EDV\Desktop\Peter\Models\*\*\002.txt")

But going into one subfolder and asking the same:

但进入一个子文件夹并询问相同:

     All_txt    = glob.glob('C:\Users\EDV\Desktop\Peter\Models\Texte\*\002.txt')

results in an empty list. Does anybody know what the problem here is (or knows another function which expresses the same)?

得到一个空列表。有谁知道这里的问题是什么(或者知道另一个表达相同的函数)?

I double-checked the folder paths and that all folders contain these text-files.

我仔细检查了文件夹路径,并且所有文件夹都包含这些文本文件。

1 个解决方案

#1


Try putting an r in front of the string to make a raw string: glob.glob(r'C:\Users\EDV\Desktop\Peter\Models\Texte\*\002.txt'). This will make it so the backslashes arent used for escaping the next character.

尝试将r放在字符串前面以生成一个原始字符串:glob.glob(r'C:\ Users \ EDV \ Desktop \ Peter \ Models \ Texte \ * \ 002.txt')。这将使反斜杠不会用于转义下一个字符。

You could also do it without glob like so:

你也可以这样做而没有像这样的全局:

import os
all_txt = []
root = r'C:\Users\EDV\Desktop\Peter\Models\Texte'
for d in os.listdir(root):
    abs_d = os.path.join(root, d)
    if os.path.isdir(abs_d):
        txt = os.path.join(abs_d, '002.txt')
        if os.path.isfile(txt):
            all_txt.append(txt)

#1


Try putting an r in front of the string to make a raw string: glob.glob(r'C:\Users\EDV\Desktop\Peter\Models\Texte\*\002.txt'). This will make it so the backslashes arent used for escaping the next character.

尝试将r放在字符串前面以生成一个原始字符串:glob.glob(r'C:\ Users \ EDV \ Desktop \ Peter \ Models \ Texte \ * \ 002.txt')。这将使反斜杠不会用于转义下一个字符。

You could also do it without glob like so:

你也可以这样做而没有像这样的全局:

import os
all_txt = []
root = r'C:\Users\EDV\Desktop\Peter\Models\Texte'
for d in os.listdir(root):
    abs_d = os.path.join(root, d)
    if os.path.isdir(abs_d):
        txt = os.path.join(abs_d, '002.txt')
        if os.path.isfile(txt):
            all_txt.append(txt)