os.listdir() / os.makedirs() / os.remove()
| Since: | Python 2(2000) |
|---|
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
| Function | Description |
|---|---|
| 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
os_listdir_basic.py
import os
entries = os.listdir('.')
print(entries)
files = [f for f in os.listdir('.') if os.path.isfile(f)]
print(files)
current = os.getcwd()
print(f'Current directory: {current}')
Running the code produces the following output:
python3 os_listdir_basic.py ['main.py', 'utils.py', 'config.json', 'data'] ['main.py', 'utils.py', 'config.json'] Current directory: /home/user/projects
os_listdir_makedirs.py
import os
os.makedirs('output/reports/2025', exist_ok=True)
print('Directory created.')
try:
os.mkdir('new_folder')
print('Folder created.')
except FileExistsError:
print('Already exists.')
with open('temp.txt', 'w') as f:
f.write('temporary file')
if os.path.exists('temp.txt'):
os.remove('temp.txt')
print('File deleted.')
Running the code produces the following output:
python3 os_listdir_makedirs.py Directory created. Folder created. File deleted.
os_listdir_walk.py
import os
with open('old_name.txt', 'w') as f:
f.write('content')
os.rename('old_name.txt', 'new_name.txt')
print('File renamed.')
for dirpath, dirnames, filenames in os.walk('.'):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
print(full_path)
Running the code produces the following output:
python3 os_listdir_walk.py File renamed. ./main.py ./utils.py ./config.json ./data/input.csv
Common Mistakes
Common Mistake 1: Not specifying exist_ok=True with os.makedirs()
Without exist_ok=True, os.makedirs() raises a FileExistsError if the directory already exists. Specifying exist_ok=True allows the script to be run any number of times without errors.
import os
os.makedirs('output/reports')
The same logic can also be written as:
import os
os.makedirs('output/reports', exist_ok=True)
Common Mistake 2: Expecting os.listdir() to traverse subdirectories
os.listdir() returns only the entry names directly inside the specified directory. Subdirectory contents are not included. To traverse directories recursively, os.walk() can be used for file operations.
import os
all_files = os.listdir('.')
print(all_files)
The same logic can also be written as:
import os
all_files = []
for dirpath, dirnames, filenames in os.walk('.'):
for filename in filenames:
all_files.append(os.path.join(dirpath, filename))
print(all_files)
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, os.walk() can be used for file operations.
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 before performing file operations.
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 contact us.