Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. os.listdir() / os.makedirs() / os.remove()

os.listdir() / os.makedirs() / os.remove()

Functions from the os module for listing directories, creating directories, deleting files, renaming files, and more. Use these functions to manipulate the filesystem from your script.

Syntax

import os

# Returns a list of file and directory names in the specified directory.
os.listdir(path)

# Creates directories recursively.
os.makedirs(path, exist_ok=True)

# Creates a single directory (raises an error if the parent does not exist).
os.mkdir(path)

# Deletes a file.
os.remove(path)

# Renames or moves a file or directory.
os.rename(old_path, new_path)

# Returns the current working directory.
os.getcwd()

# Changes the current working directory.
os.chdir(path)

Function List

FunctionDescription
os.listdir(path)Returns a list of entry names (files and subdirectories) in the specified directory. The order is arbitrary, and . and .. are not included.
os.makedirs(path, exist_ok=False)Creates the specified directory path recursively. Setting exist_ok=True prevents an error if the directory already exists.
os.mkdir(path)Creates a single directory. Raises FileNotFoundError if the parent directory does not exist.
os.remove(path)Deletes a file. Cannot be used on directories. Raises FileNotFoundError if the file does not exist.
os.rename(old_path, new_path)Renames or moves a file or directory.
os.getcwd()Returns the absolute path of the current working directory as a string.
os.chdir(path)Changes the current working directory.
os.rmdir(path)Deletes an empty directory. Raises OSError if the directory is not empty.

Sample Code

import os

# Use listdir() to get the contents of a directory.
entries = os.listdir('.')  # Get a list of entries in the current directory.
print(entries)  # Prints a list of file and directory names.

# Filter for files only.
files = [f for f in os.listdir('.') if os.path.isfile(f)]
print(files)

# Use makedirs() to create nested directories all at once.
os.makedirs('output/reports/2025', exist_ok=True)
print('Directory created.')

# mkdir() can only be used when the parent directory already exists.
try:
    os.mkdir('new_folder')
    print('Folder created.')
except FileExistsError:
    print('Already exists.')

# Use getcwd() to check the current directory.
current = os.getcwd()
print(f'Current directory: {current}')

# Delete a file.
with open('temp.txt', 'w') as f:
    f.write('temporary file')

if os.path.exists('temp.txt'):
    os.remove('temp.txt')
    print('File deleted.')

# Use rename() to rename a file.
with open('old_name.txt', 'w') as f:
    f.write('content')
os.rename('old_name.txt', 'new_name.txt')
print('File renamed.')

# Use os.walk() to traverse directories recursively.
for dirpath, dirnames, filenames in os.walk('.'):
    for filename in filenames:
        full_path = os.path.join(dirpath, filename)
        print(full_path)

Notes

os.listdir() returns only the entry names directly inside the specified directory. It does not include the contents of subdirectories. To traverse directories recursively, use os.walk() instead.

With os.makedirs(), specifying exist_ok=True prevents an error if the directory already exists. This is useful for writing idempotent scripts — ones that produce the same result no matter how many times you run them.

Files deleted with os.remove() are permanently removed and do not go to the trash. Always confirm before deleting, or back up important files beforehand.

For path manipulation, see os.path.join() / os.path.exists() / os.path.basename(). For a more modern approach to path handling, see pathlib.Path().

If you find any errors or copyright issues, please .