SoFunction
Updated on 2025-04-29

Get a list of files and subdirectories in a specified directory in Python

() function

()Yes PythonosA function in the module that gets a list of files and subdirectories in a specified directory. It returns a list containing the contents of the directory, but does not recursively enter the subdirectory.

1. ()  Syntax

import os

(path=".")

parameter:

  • path(Optional): The path to list files and directories, default to the current directory (.)。
  • Return value: A list containing the names of files and subdirectories in the specified directory (excluding paths).

Return type:

  • List (list), the elements in which are the names (strings) of the file and directory.

2. Basic usage examples

2.1 List all files and folders in the current directory

import os

# List all files and subdirectories in the current directoryfile_list = ()
print(file_list)

2.2 List all files and subdirectories in the specified directory

import os

# Specify a directorypath = "/path/to/directory"

# List all files and subdirectories in this directoryfile_list = (path)
print(file_list)

3. Cooperate and filter

3.1 Distinguish between files and directories

()Return only the name. If you want to distinguish between files and directories, you need to use()and()

import os

path = "/path/to/directory"
all_items = (path)

# Filter out filesfiles = [f for f in all_items if ((path, f))]
print("Files:", files)

# Filter out the directorydirectories = [d for d in all_items if ((path, d))]
print("Directories:", directories)

4. Combined with glob and fnmatch for filtering

If you want to obtain a specific type of file (such as .txt, .jpg, etc.), you can combine glob or fnmatch for filtering.

4.1 Use glob to obtain specific types of files

import glob

# Get all .txt files in the current directorytxt_files = ("*.txt")
print(txt_files)

4.2 Use fnmatch for file matching

import os
import fnmatch

path = "/path/to/directory"
all_files = (path)

# Match only .txt filestxt_files = [f for f in all_files if (f, "*.txt")]
print(txt_files)

5. Traverse all files (including subdirectories)

()Only return the contents under the current directory and will not recursively enter the subdirectory. If you need to traverse all subdirectories, you can use()

import os

path = "/path/to/directory"

for root, dirs, files in (path):
    print("Current directory:", root)
    print("Subdirectories:", dirs)
    print("Files:", files)

6. Use in combination with sorted()

OK()The returned list is sorted by name, size, or modification time.

6.1 Sort by file name

import os

path = "/path/to/directory"
sorted_list = sorted((path))
print(sorted_list)

6.2 Sort by file size

import os

path = "/path/to/directory"
files = (path)

# Get a list of files sorted by sizesorted_files = sorted(files, key=lambda f: ((path, f)))

print(sorted_files)

6.3 Sort by modification time

import os

path = "/path/to/directory"
files = (path)

# Get a list of files sorted by modification timesorted_files = sorted(files, key=lambda f: ((path, f)))

print(sorted_files)

7. () vs ()

After Python 3.5, it is recommended to use(), it is better than()More efficient, and can directly obtain file type, size and other information.

import os

path = "/path/to/directory"

with (path) as entries:
    for entry in entries:
        print(f"Name: {}, Is file: {entry.is_file()}, Is directory: {entry.is_dir()}")

8. Summary

method illustrate
(path) Get all files and subdirectories in the directory (excluding paths)
(path) Determine whether the path is a file
(path) Determine whether the path is a directory
(path) Recursively traverse all files and subdirectories in the directory
(path) More efficient directory traversal
sorted((path)) Sort by file name
("*.txt") Get the file of the specified type

This is the article about obtaining a list of files and subdirectories in a specified directory in Python. For more related Python () To obtain the content of directory files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!