It is often used when you want to easily get the file name in a folder. Click here for the source http://svn.python.org/view/python/branches/release27-maint/Lib/glob.py?view=markup If you have a folder like the one below
terminal.
$ ls
0.csv 2.txt 5.csv 7.txt test_glob.py
0.txt 3.csv 5.txt 8.csv
1.csv 3.txt 6.csv 8.txt
1.txt 4.csv 6.txt 9.csv
2.csv 4.txt 7.csv 9.txt
test_glob.py
import glob
text_fnames = glob.glob('./*.txt')
print text_fnames
output.
$ python test_glob.py
['./0.txt', './1.txt', './2.txt', './3.txt', './4.txt', './5.txt', './6.txt', './7.txt', './8.txt', './9.txt']
In this way, you can easily get the txt file in the file by setting it to * .txt.
The argument of glob.glob is a string, and it is written in the same way as the shell.
Both relative and absolute paths can be used as arguments.
Also, if you change glob.glob to glob.iglob, the iterator will come back.
Unless the number of files is huge, I think that glob.glob is enough.
In the source content, glob.iglob creates file names one by one with yeild.
glob.glob (pathname) is just like list (glob.iglob (pathname)).
The rest is a simple code to search using the ʻos` module.
Recommended Posts