Learn Python
>>> file_handling.file_dir_operations

Renaming, Deleting & Directory Operations in Python

#concept

Beyond reading and writing file contents, Python's os and os.path modules provide tools for managing the files and folders themselves — renaming, deleting, checking whether something exists, and creating or listing directories. These operations talk directly to the operating system's file system, so they behave consistently across whatever platform the code runs on.

#how it works
1

os.rename("old", "new")

Renames a file or directory.

2

os.remove() and os.rmdir()

Delete a single file, or an empty directory, respectively.

3

os.path.exists("path")

Checks whether a file or directory exists, before trying to work with it.

4

os.mkdir() and os.listdir()

Create a new directory, or list everything inside an existing one.

5

os.path.join(...)

Builds a correct file path for the current operating system, avoiding hardcoded slashes that might not work everywhere.

#example
import os
 
os.mkdir("temp_folder")
print(os.path.exists("temp_folder"))
 
with open(os.path.join("temp_folder", "note.txt"), "w") as f:
f.write("hello")
 
print(os.listdir("temp_folder"))
 
os.remove(os.path.join("temp_folder", "note.txt"))
os.rmdir("temp_folder")
print(os.path.exists("temp_folder"))
Output
True
['note.txt']
False
1os.mkdir("temp_folder") creates a new, empty directory, and os.path.exists confirms it now exists.
2os.path.join builds a correct path to a file inside that folder, working the same way regardless of the operating system’s slash style.
3os.listdir("temp_folder") shows exactly one file, note.txt, sitting inside the new directory.
4Removing the file and then the now-empty directory cleans everything up, and the final exists check confirms the folder is genuinely gone.
#use cases
Organizing a program's output files into folders, creating directories as needed with os.mkdir()
Checking a file exists before trying to open it, avoiding a crash from a missing file
Cleaning up temporary files a program created during its run
Building file paths that work correctly on Windows, macOS, and Linux alike, using os.path.join() instead of hardcoded slashes

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.