List All Files in a Directory using Python

To list all files in a directory using Python, you can use the os and pathlib modules. The os.listdir() function retrieves filenames in a directory, while os.walk() and pathlib.Path().iterdir() provide more advanced directory traversal options. Below are different ways to achieve this with examples.


Examples to List All Files in a Directory

1. Listing Files in a Directory Using os.listdir()

In this example, we will use the os.listdir() function to retrieve all files and directories in a specified folder.

main.py

</>
Copy
import os

# Specify the directory path
directory_path = "/Users/tutorialkart/example_dir/"

# Get a list of all files and directories
all_files = os.listdir(directory_path)

# Print the result
print("Files and Directories:", all_files)

Explanation:

  1. Import the os module to interact with the operating system.
  2. Define directory_path with the folder path to be scanned.
  3. Use os.listdir(directory_path) to fetch all file and folder names.
  4. Store the results in all_files and print the list.

Output:

2. Listing Only Files in a Directory Using os and os.path

Here, we filter out directories and list only files using os.path.isfile().

main.py

</>
Copy
import os

# Specify the directory path
directory_path = "C:/Users/YourUsername/Documents"

# Get only files (exclude directories)
only_files = [f for f in os.listdir(directory_path) if os.path.isfile(os.path.join(directory_path, f))]

# Print the list of files
print("Files:", only_files)

Explanation:

  1. Import the os module.
  2. Define directory_path with the directory location.
  3. Use a list comprehension to iterate over os.listdir(directory_path) and filter only files using os.path.isfile().
  4. Print the filtered file names stored in only_files.

Output:

Files: ['file1.txt', 'file2.pdf', 'script.py']

3. Using os.walk() to List All Files Recursively

To list all files in a directory and its subdirectories, we use os.walk().

main.py

</>
Copy
import os

# Specify the directory path
directory_path = "/Users/tutorialkart/Documents"

# Traverse the directory and list all files
for root, dirs, files in os.walk(directory_path):
    for file in files:
        print(os.path.join(root, file))

Explanation:

  1. Import the os module.
  2. Define directory_path with the target folder.
  3. Use os.walk(directory_path) to traverse subdirectories.
  4. Loop through files in each directory and print the full path using os.path.join(root, file).

Output:

/Users/tutorialkart/Documents/file1.txt
/Users/tutorialkart/Documents/file2.pdf
/Users/tutorialkart/Documents/subfolder/script.py

4. Listing Files Using pathlib

The pathlib module provides an object-oriented approach to handling files and directories.

main.py

</>
Copy
from pathlib import Path

# Specify the directory path
directory_path = Path("/Users/tutorialkart/Documents")

# Get a list of files
files = [file.name for file in directory_path.iterdir() if file.is_file()]

# Print the list of files
print("Files:", files)

Explanation:

  1. Import Path from the pathlib module.
  2. Create a Path object for directory_path.
  3. Use iterdir() to iterate through directory contents.
  4. Filter files using is_file() and extract names.
  5. Print the resulting list of files.

Output:

Files: ['file1.txt', 'file2.pdf', 'script.py']

Conclusion

Here are four ways to list files in a directory:

  1. os.listdir(): Lists all files and folders in a directory.
  2. os.path.isfile(): Filters only files.
  3. os.walk(): Lists all files recursively.
  4. pathlib.Path().iterdir(): Provides an object-oriented way to list files.

Choose the method that best fits your use case!