glob Module in Python

glob Module in Python

Thanks to glob module, we can use wildcards with Python in finding pathnames.

>>> import glob
>>> dir(glob)
[‘__all__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__initializing
__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘fnmatch’, ‘glob’, ‘glob0’, ‘glob1
‘, ‘has_magic’, ‘iglob’, ‘magic_check’, ‘magic_check_bytes’, ‘os’, ‘re’]
>>>

You can see that glob module contains other modules: os, re, and fnmatch. So it’s a very powerful.

Let’s see the functions:

glob

>>> glob.glob(“D:/”)
[‘D:/’]
>>> for f in glob.glob(“*.txt”):
…     print(f)

ert.txt
et.txt
LICENSE.txt
NEWS.txt
README.txt
>>>

>>> for f in glob.glob(“D:/*.txt”):
…     print(f)

D:/artyk.txt
D:/derek.txt
D:/dereka.txt
D:/pliczek.txt
>>>

>>> for f in glob.glob(“D:/*.*”):
…     print(f)

D:/ale.csv
D:/artyk.txt
D:/cs14.cs
D:/derek.txt
D:/dereka.txt
D:/Photo0045.jpg
D:/Photo0046.jpg
D:/Photo0047.jpg
D:/Photo0048.jpg
D:/Photo0058.jpg
D:/pliczek.txt
D:/processlist.csv
D:/processlist.html
D:/processlist.xml
>>>

>>> f = glob.glob(“D:/*.*”)
>>> print(f)

>>> print(f)
[‘D:/408998_10151307870152631_1487917839_n.jpg’, ‘D:/970107_449345235148911_6212
97987_n.jpg’, …, ‘D:/zeta.csv’]
>>>

Glob is used to get a list of items.

iglob

>>> f = glob.iglob(“D:/*.*”)
>>> print(f)
<generator object iglob at 0x00C7B490>
>>> for g in f:
…     print(g)

D:/408998_10151307870152631_1487917839_n.jpg
D:/970107_449345235148911_621297987_n.jpg
D:/ale.csv
D:/artyk.txt
D:/cbsidlm-cbsi5_4_0_104-Advanced_SystemCare-BP-10407614.exe
D:/derek.txt
D:/dereka.txt
D:/eta.csv
D:/Photo0045.jpg
D:/Photo0046.jpg
D:/Photo0047.jpg
D:/Photo0048.jpg
D:/Photo0058.jpg
D:/processlist.csv
D:/processlist.html
D:/processlist.xml
D:/zeta.csv
>>>

>>> list(glob.iglob(“D:/*.txt”))
[‘D:/artyk.txt’, ‘D:/derek.txt’, ‘D:/dereka.txt’, ‘D:/pliczek.txt’]
>>>

So iglob is used to get an generator.

>>> f = glob.iglob(“D:/*.txt”)
>>> f
<generator object iglob at 0x00C7EC38>

We can get an item from our generator one by one:

>>> f.__next__
<method-wrapper ‘__next__’ of generator object at 0x00C7EC38>
>>> f.__next__()
‘D:/artyk.txt’
>>> f.__next__()
‘D:/derek.txt’
>>> f.__next__()
‘D:/dereka.txt’
>>>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s