What is the Glob module in Python?
Time is money, I will make no intros, Let's get straight to the point.
Glob is a python built-in module, which is helpful in finding files using a pattern specified.
It matches all the files that are specified with the pattern. You need to pass a pattern to the glob()
function. It will return a list of all files path that matches that pattern.
Look at the following example
Example: Find all HTML files in a directory and all subdirectories?
Look at the following screenshot. There are directories and subdirectories containing different types of files. I want to get the list of all HTML files.
To achieve the result we will use the python glob module. the following few lines of code will do the job for us.
import glob
# path to search file
path = './'
# add another param to glog() funciton
for file in glob.glob(path+"**/*.html", recursive=True):
print(file)
Now we can do the same job using regular expressions. Just like the below code. We have used regular expressions to achieve the same result.
import re
import os
currentdir = os.getcwd()
files = os.listdir(currentdir)
pattern = "^*.html$"
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)
Why use glob module if we have regex in python
The answer is simple. Python glob module is designed, especially to work with files pattern, and believe me it does the job very effectively. Now one can achieve the same result with regex but with more control over it. So it is up to you.
Please ???
Please leave a like if this post is helpful to you. And, wait, please also have a look on my youtube channel.
更多推荐
所有评论(0)