TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python Glob Module – Glob() Method
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python Glob Module – Glob() Method

Last updated: Oct 27, 2023 12:43 am
By Meenakshi Agarwal
Share
4 Min Read
Python glob method with examples
Python glob method with examples
SHARE

This tutorial provides an overview of the Python glob() method of the glob module. It includes several examples to bring clarity.

Contents
glob(file_pattern, recursive = False)Check the current directory for Python script filesList files with a patterniglob() method | Python Globescape() method

Introduction

Usually, the programmers are required to traverse through a list of files at some location, mostly having a specific pattern.

The glob module in Python has several functions that can help in listing files under a specified folder. We may filter them based on extensions or with a particular string as a portion of the filename.

All the methods of the Glob module follow the Unix-style pattern-matching mechanism and rules. However, it doesn’t allow expanding the tilde (~) and environment variables.

Python Glob() Methods

Today, we are going to discuss three primary functions of the Glob module.

glob(file_pattern, recursive = False)

It retrieves the list of files matching the specified Python pattern in the file_pattern parameter.

The file_pattern can be an absolute or relative path. It may also contain wild cards such as “*” or “?” symbols.

The recursive parameter is turned off (False) by default. When True, it recursively searches files under all subdirectories of the current directory.

Let’s now check out some examples:

Check the current directory for Python script files

The below code checks for .py files in the current dir only.

>>> import glob
>>> for py in glob.glob("*.py"):
...    print(py)
...
copy_file1.py
copy_file2.py
decimal_sample.py

Another sample code – It checks for .py files in the current dir and subdirectories.

>>> import glob
>>> for py in glob.glob("*.py"):
...    print(py)
...
copy_file1.py
copy_file2.py
decimal_sample.py
test_num.py
test_python_in_with_if.py
test_scope.py

List files with a pattern

We can provide a pathname pattern by including some wild cards like? or numeric range [0-9].  The below code lists all files whose name starts with “test” followed by a number.

>>> for py in glob.glob("test[0-9].py"):
...    print(py)
...
test1.py
test2.py

Let’s check one more example using the question mark in the pattern.

>>> for py in glob.glob("?????.py"):
...    print(py)
...
quiz1.py
test1.py
test2.py

The above Python for loop statement printed all .py files having five letters.

The following statement would print the names of folders recursively in the current working directory.

>>> glob.glob('selenium/**/', recursive=True)
['selenium\\', 'selenium\\webdriver\\', 'selenium\\webdriver\\firefox\\', 'selen
ium\\webdriver\\firefox\\amd64\\', 'selenium\\webdriver\\firefox\\x86\\']

iglob() method | Python Glob

This method creates a Python generator object which can be used to list files under a given directory. You can call the next() function to print the names of files.

Check the sample code below:

>>> gen = glob.iglob("*.py")
>>> type(gen)
<class 'generator'>
>>> for py in gen:
...    print(py)
...
copy_file1.py
copy_file2.py
decimal_sample.py
find_seed.py
frozen_set.py

escape() method

It allows for escaping the given character sequence. You can find it handy for locating files with certain characters in their file names.

Check out the below examples:

>>> char_seq = "-_#"
>>> for spcl_char in char_seq:
...    esc_set = "*" + glob.escape(spcl_char) + "*" + ".py"
...    for py in (glob.glob(esc_set)):
...       print(py)
...
python quiz-classes-2.py
python-class.py
python-lists.py
python-random#num.py
python-set.py
python-tuples.py
python-while_loop.py
copy_file#2.py
decimal_sample.py
find_seed.py
frozen-set.py

Must check out – Python to list all files in a directory

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Python list all files in a directory Python List All Files in a Directory
Next Article Python lambda usage with examples Lambda Function Usage in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x