Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用glob读取有限的带有数字名称的文件集?_Python_Path_Glob - Fatal编程技术网

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

Python 如何使用glob读取有限的带有数字名称的文件集?,python,path,glob,Python,Path,Glob,如何使用glob只读取有限的文件集 我在同一个目录中有名为50到20000的json文件(例如50.json、51.json、52.json…19999.json、20000.json)。我只想读取编号为15000到18000的文件 为了做到这一点,我使用了一个glob,如下所示,但每次我尝试筛选出数字时,它都会生成一个空列表。我已经尽了最大努力去关注这个链接(),但是我不确定我做错了什么 >>> directory = "/Users/Chris/Dropbox" >&

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

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

为了做到这一点,我使用了一个glob,如下所示,但每次我尝试筛选出数字时,它都会生成一个空列表。我已经尽了最大努力去关注这个链接(),但是我不确定我做错了什么

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

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

您使用的glob语法不正确;
[…]
序列对每个字符有效。以下glob将与您的文件正确匹配:

'1[5-8][0-9][0-9][0-9].*'
在封面下,
glob
使用
fnmatch
将模式转换为正则表达式。您的模式转换为:

>>> import fnmatch
>>> fnmatch.translate('[15000-18000].*')
'[15000-18000]\\..*\\Z(?ms)'
它与
前面的1个字符、a
0
1
5
8
匹配。没有别的了

glob
模式非常有限;匹配数字范围并不容易;您必须为范围创建单独的全局,例如(
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)
directory=“/Users/Chris/Dropbox”
对于os.listdir(目录)中的文件名:
basename,ext=os.path.splitext(文件名)
如果ext!='。json':
持续
尝试:
number=int(基本名称)
除值错误外:
继续#不是数字

如果18000虽然算不上漂亮的代码,但您可以实现自己的过滤,如下所示:

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
这里的关键行(应该)遍历目录中的每个文件名(
对于所有文件中的这个文件
),拉出该文件名中的数字段列表(
re.findall(“\d+”,这个文件)
),如果最后一个数字段作为整数大于18000,则将其包含在
读取文件

我认为这将在名称中没有整数的文件上中断,所以用户要小心



编辑:我看到前面的答案已被编辑,其中包含了一种经过深思熟虑的方法。

如果我只想在18000年后读取文件,该怎么办。你有什么建议吗?数字有多高
glob
确实非常有限;从目录中读取所有文件名,然后进行筛选。你可以自己过滤。随着时间的推移,文件会被添加。每天大约生成50个文件,我的文件是19000。我在实现18000到29000时遇到了问题:“/[1-2][0-9][0-9][0-9][0-9].*”,因为我不希望10000实现18000@Chris:
glob
确实不适合那个任务。明白了,很高兴知道。谢谢-不管怎样,这对我帮助很大。