如何使用glob来读取带有数字名称的有限文件集?

Chr*_*ris 8 python glob path

如何使用glob只读取有限的文件集?

我在同一目录中有名为50到20000的json文件(例如50.json,51.json,52.json ... 19999.json,20000.json).我想只读取编号为15000到18000的文件.

为此,我使用了一个glob,如下所示,但每当我尝试过滤掉数字时它会生成一个空列表.我已经尽力遵循这个链接(https://docs.python.org/2/library/glob.html),但我不确定我做错了什么.

>>> directory = "/Users/Chris/Dropbox"
>>> read_files = glob.glob(directory+"/[15000-18000].*")
>>> print read_files
[]
Run Code Online (Sandbox Code Playgroud)

另外,如果我想要任何数字大于18000的文件怎么办?

Mar*_*ers 12

您正在使用glob语法错误; 该[..]序列的作品每个字符.以下glob将正确匹配您的文件:

'1[5-8][0-9][0-9][0-9].*'
Run Code Online (Sandbox Code Playgroud)

在封面下,glob用于fnmatch将模式转换为正则表达式的用法.您的模式转换为:

>>> import fnmatch
>>> fnmatch.translate('[15000-18000].*')
'[15000-18000]\\..*\\Z(?ms)'
Run Code Online (Sandbox Code Playgroud)

在a ,a ,或之前匹配1个字符.没有其他的..0158

glob模式非常有限; 匹配数值范围并不容易; 你必须为范围创建单独的 globs,例如(glob('1[8-9][0-9][0-9][0-9]') + glob('2[0-9][0-9][0-9][0-9]')等).

做你自己的过滤:

directory = "/Users/Chris/Dropbox"

for filename in os.listdir(directory):
    basename, ext = os.path.splitext(filename)
    if ext != '.json':
        continue
    try:
        number = int(basename)
    except ValueError:
        continue  # not numeric
    if 18000 <= number <= 19000:
        # process file
        filename = os.path.join(directory, filename)
Run Code Online (Sandbox Code Playgroud)

  • 数字有多高?`glob`真的非常有限; 从目录中读取所有文件名,然后进行过滤.您可以随时进行自己的过滤. (2认同)
  • 好吧,随着时间的流逝,文件正在被添加。每天大约生成50个文件,而我的文件是19000。我在用以下方法实现18000到29000时遇到问题:“ / [1-2] [0-9] [0-9] [0-9] [ 0-9]。*“,因为我不希望10000到18000 (2认同)
  • @Chris:`glob`确实不适合该任务。 (2认同)

小智 5

尽管它算不上漂亮的代码,但您可以实现自己的过滤,如下所示:

import os, re
directory = "/Users/Chris/Dropbox"
all_files = os.listdir(directory)

read_files = [this_file for this_file in all_files 
                if (int(re.findall('\d+', this_file)[-1]) > 18000)]

print read_files
Run Code Online (Sandbox Code Playgroud)

这里的关键行(应该)迭代目录中的每个文件名(for this_file in all_files),提取该文件名中的数字段列表(re.findall('\d+', this_file)),read_files如果这些数字段中的最后一个(作为整数)更大,则将其包含在其中超过18000。

我认为这会破坏名称中没有整数的文件,所以用户要小心。


编辑:我看到之前的答案已被编辑,以包含看起来更好的深思熟虑的方法来做到这一点。