简体   繁体   中英

python glob matching patterns

I am looking at the glob man page and I cannot make the matching patterns work in python. I have this so far...

glob.glob('file.*') + glob.glob('file[0-9].*')

and this works and return me a list as long as the file numbers o not exceed 9. If I make a file100.txt it does not work, and if I try the range [0-100] or [0-1000] it does not change anything...

So my question is how can I make this match any number....and also how can I combine it into one statement, it seems like it should be once statement.

I'm pretty sure glob isn't expressive enough to do what you want, so I suggest fetching more than you need and then filtering. Eg (untested)

import re

file_names = [name for name in glob.glob('file*.*') if re.match(r'^file\d*\.', name]

Ordinary globbing doesn't handle that type of thing. You can't specify repetitions of specific patterns of characters. You won't be able to do it with a single call. Your best bet is to just use file*.txt , and then post-process the resulting list to eliminate ones not matching your pattern, for instance by using regular expressions functions in the re module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM