Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

glob "one or more" in Python

Tags:

python

glob

I need to get all text files with numeric names: 1.txt, 2.txt, 13.txt
Is it possible to do with glob?

import glob

for file in glob.glob('[0-9].txt'):
    print(file)

Does not return 13.txt.
And there seems to be no regex's one or more + operator.

What can I do?

like image 447
Qiao Avatar asked Oct 10 '22 13:10

Qiao


2 Answers

I don't think that glob() is meant to be that customisable. You might want to try os.listdir() instead:

import os,re
for f in os.listdir("/path/to/dir"):
    if re.match(r"^\d+\.txt$", f):
        print(f)
like image 183
Daniel Quinn Avatar answered Oct 12 '22 09:10

Daniel Quinn


From TFM:

No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched

So, no, there are no + operators as in regex. You can use glob as a first-pass (as in glob('*.txt')), and filter it further with regex.

like image 29
Brian Cain Avatar answered Oct 12 '22 10:10

Brian Cain