Renaming, Deleting & Directory Operations in Python
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.
os.rename("old", "new")
Renames a file or directory.
os.remove() and os.rmdir()
Delete a single file, or an empty directory, respectively.
os.path.exists("path")
Checks whether a file or directory exists, before trying to work with it.
os.mkdir() and os.listdir()
Create a new directory, or list everything inside an existing one.
os.path.join(...)
Builds a correct file path for the current operating system, avoiding hardcoded slashes that might not work everywhere.
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"))Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.