ποΈ Python OS File/Directory Methods β Create, Rename, Delete & Navigate
π§² Introduction β Why Use the os
Module?
Pythonβs built-in os
module lets you interact with the operating system, allowing you to work with files, folders, and directories programmatically. Whether you need to create, rename, move, delete, or navigate directories, os
provides platform-independent functions to automate these tasks.
π― In this guide, you’ll learn:
- Core
os
module methods for file/directory handling - How to list, rename, delete, and navigate folders
- Best practices for checking and manipulating paths
π¦ Importing the os
Module
import os
β This module provides all file/directory-related functions.
π Directory Management Methods
β
os.getcwd()
β Get Current Working Directory
print(os.getcwd())
β Returns the absolute path of the current working directory.
β
os.chdir(path)
β Change Directory
os.chdir("/path/to/folder")
β Changes the current working directory to the specified path.
β
os.listdir(path='.')
β List Files/Folders
print(os.listdir())
β Lists all files and directories in the given path (default: current directory).
β
os.mkdir("folder")
β Create New Directory
os.mkdir("new_folder")
β Creates a new directory (fails if it already exists).
β
os.makedirs("path/to/nested/folder")
os.makedirs("folder1/folder2/folder3")
β Recursively creates nested directories.
β
os.rmdir("folder")
β Remove Empty Directory
os.rmdir("new_folder")
β
Deletes an empty folder. Use shutil.rmtree()
for non-empty folders.
π File Handling with OS Methods
β
os.remove("file.txt")
β Delete File
os.remove("data.txt")
β Permanently deletes the specified file.
β
os.rename("old.txt", "new.txt")
os.rename("old_name.txt", "new_name.txt")
β Renames or moves a file.
β
os.path.exists(path)
β Check if File/Dir Exists
if os.path.exists("myfile.txt"):
print("Exists!")
β Safely checks whether the file or folder exists before performing operations.
β
os.path.isdir(path)
/ os.path.isfile(path)
os.path.isdir("my_folder")
os.path.isfile("file.txt")
β Distinguishes between files and directories.
β
os.path.join()
β Join Path Components
path = os.path.join("folder", "file.txt")
print(path) # Output: folder/file.txt (platform-independent)
β
Safely concatenates paths using the correct separator (/
or \
depending on OS).
π§Ή Cleanup & Recursive Operations
For non-empty folder deletion, use:
import shutil
shutil.rmtree("folder_name")
β Recursively deletes a folder and all its contents.
π‘ Best Practices
- β
Always check file/folder existence with
os.path.exists()
before removing or renaming. - β
Use
os.path.join()
to maintain cross-platform compatibility. - β
Use
with open()
for file access alongsideos
for management. - β οΈ Donβt use
os.rmdir()
on non-empty foldersβuseshutil.rmtree()
.
π Summary β Recap & Next Steps
The os
module is a powerful tool for automating filesystem tasks like directory navigation, file manipulation, and structural organization. It simplifies batch file processing, backup scripts, and file-based automation across platforms.
π Key Takeaways:
- β
Use
os.getcwd()
,os.chdir()
, andos.listdir()
for directory navigation - β
Use
os.mkdir()
,os.makedirs()
,os.remove()
,os.rename()
for filesystem changes - β
Check existence and join paths safely with
os.path
functions
βοΈ Real-World Relevance:
Used in deployment scripts, log file rotation, automated backups, and data preprocessing pipelines.
β FAQ Section β Python OS File/Directory Methods
β How do I check if a file exists before deleting it?
β Use:
if os.path.exists("file.txt"):
os.remove("file.txt")
β Whatβs the difference between os.mkdir()
and os.makedirs()
?
β
mkdir()
creates one folder. makedirs()
creates nested directories recursively.
β How do I delete a folder that contains files?
β Use:
import shutil
shutil.rmtree("folder_name")
β Can I join folder and file names safely?
β
Use os.path.join("folder", "file.txt")
β works on all operating systems.
β Whatβs the difference between os.path.isdir()
and isfile()
?
β
isdir()
checks for a folder. isfile()
checks for a regular file.
Share Now :