Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to ignore hidden files using os.listdir() in Python?
When working with directories in Python, hidden files can clutter your file listings. Hidden files start with a dot (.) on Unix-like operating systems and can be easily filtered out using various Python techniques.
In this article, we will explore different methods to ignore hidden files using the os module and pathlib.
Using List Comprehension with os.listdir()
The os.listdir() method includes hidden files (those starting with a dot) in its results. To filter out hidden files and list only visible files, we can use list comprehension with a condition ?
import os
# List all non-hidden files
visible_files = [file for file in os.listdir('.') if not file.startswith('.')]
print("Visible files:", visible_files)
print("Total visible files:", len(visible_files))
Visible files: ['config.py', 'data.txt', 'helper.py', 'main.py'] Total visible files: 4
Using a For Loop to Filter Files
We can use a for loop to iterate through files returned by os.listdir() and manually filter out hidden files ?
import os
print("Non-hidden files:")
for file in os.listdir('.'):
if not file.startswith('.'):
print(f" - {file}")
Non-hidden files: - config.py - data.txt - helper.py - main.py
Using Helper Function for Reusability
Creating a helper function makes your code more reusable and readable. This approach separates the filtering logic into a dedicated function ?
import os
def is_visible_file(filename):
"""Check if a file is visible (not hidden)."""
return not filename.startswith('.')
def get_visible_files(directory='.'):
"""Get all visible files from a directory."""
return [f for f in os.listdir(directory) if is_visible_file(f)]
# Use the helper functions
visible_files = get_visible_files()
print("Visible files found:")
for file in visible_files:
print(f" {file}")
Visible files found: config.py data.txt helper.py main.py
Using pathlib.Path.iterdir() Method
The pathlib module provides an object-oriented approach to handle file system paths. The Path.iterdir() method can iterate over directory items and filter hidden files ?
from pathlib import Path
# Get current directory path
current_dir = Path('.')
# Get visible files using pathlib
visible_files = [file.name for file in current_dir.iterdir()
if file.is_file() and not file.name.startswith('.')]
print("Visible files using pathlib:")
for file in visible_files:
print(f" {file}")
Visible files using pathlib: config.py data.txt helper.py main.py
Comparison of Methods
| Method | Readability | Reusability | Best For |
|---|---|---|---|
| List Comprehension | High | Medium | One-time filtering |
| For Loop | High | Low | Simple iteration |
| Helper Function | Very High | Very High | Repeated use |
| pathlib | High | High | Modern Python code |
Conclusion
Use list comprehension for simple one-time filtering, helper functions for reusable code, and pathlib for modern object-oriented file handling. All methods effectively filter hidden files starting with a dot.
