DEV Community

Cover image for How does glob work in Python?
AlixaProDev
AlixaProDev

Posted on

How does glob work in Python?

Python is famous for huge list of ready made modules. These ready made modules can make our lives much easier if we make use of them.

Recently I have started exploring different Python modules. In this Short tutorial I will introduce you to the glob module.

If you do not what a module is Please read this.

What the hack is glob module in Python?

In general Programming the term 'glob' means 'global'. You can read the full history on the Wikipedia.

To make things simple, glob is a way of searching for files matches to a specific pattern.

Wait, but you have regular expression that do the job? Yes, you have regular expression but glob modules makes things way more easier than regular expression if you are dealing with files.

Install glob module in Python?

Lets, get our hands dirty on glob module by first installing it. It is a python built in module, I know that.

But to be on the safe side you can use the following command on your terminal to install glob module.

pip install glob2

Make sure you have python installed and you have pip set up.

Example of using glob module

The best way to learn something is to learn it by example.

In this example we will use python glob module to find mp4 files available in all sub directories along with the root.

Check the following code.

import glob
path = './'
curfiles = glob.glob(path + '**/*.mp4',recursive=True)
for file in curfiles:
    print(file)
Enter fullscreen mode Exit fullscreen mode

The same result can be achieved using regular expression.

import re
import os
currentdir = os.getcwd()
files = os.listdir(currentdir)
pattern = "^*.mp4$"
prog = re.compile(pattern)
htmlfiles=[]
for file in files:
    result = prog.findall(file)
    if len(result)!=0:
        htmlfiles.append(result[0])

for htmlfile in htmlfiles:
    print(htmlfile)
Enter fullscreen mode Exit fullscreen mode

Words From My Heart

I am so thankful to you for reading this piece of article. I will be more than happy and pleased if you leave a like, comment on it.

PS: Please check out my YouTube channel if you love coding videos. [Code With Ali]

Top comments (0)