Python glob hidden files

Python glob hidden files

The Python glob module provides a convenient way to retrieve files and directories in a specified pattern matching. By default, the glob module doesn’t list hidden files or directories that start with a dot (.), but you can use a specific pattern to include them in the result.

To retrieve hidden files with Python glob, you can use the os module in conjunction with the glob module. Here’s an example:

import os
import glob

# List all files, including hidden files, in a directory
hidden_files = glob.glob(os.path.join('/path/to/directory', '.*'))

for file in hidden_files:
    print(file)
  

In the code above, we import the os and glob modules. We then use the os.path.join() function to create the file pattern, combining the directory path with .* to match all hidden files. The glob.glob() function retrieves all matching files, including hidden files, and stores them in the hidden_files list. Finally, we iterate over the list and print the file paths.

Let’s consider an example where we have a directory named “files” with the following files, including hidden files:

  • file1.txt
  • .hidden1.txt
  • .hidden2.py
  • .hidden3.jpg
  • file2.txt

With the code provided, the output will be:

.hidden1.txt
.hidden2.py
.hidden3.jpg
  

As you can see, the code successfully retrieves the hidden files in the specified directory.

Leave a comment