The os module in Python provides powerful functions for file and directory operations, including creating, renaming, deleting, and checking file properties.


๐Ÿ”น Importing the os Module

import os

๐Ÿ”น 1๏ธโƒฃ Checking if a File Exists (os.path.exists())

Before performing file operations, it’s a good practice to check if the file exists.

file_path = "example.txt"

if os.path.exists(file_path):
    print("File exists!")
else:
    print("File does not exist.")

โœ… Use Case: Prevent errors when accessing a file.


๐Ÿ”น 2๏ธโƒฃ Creating a New File (open() + os.path.exists())

  • If the file does not exist, create it using open().
file_path = "example.txt"

if not os.path.exists(file_path):
    open(file_path, "w").close()
    print("File created!")
else:
    print("File already exists.")

โœ… Use Case: Ensure files are available before writing.


๐Ÿ”น 3๏ธโƒฃ Renaming a File (os.rename())

os.rename("example.txt", "new_example.txt")
print("File renamed successfully!")

โœ… Use Case: Updating filenames dynamically.


๐Ÿ”น 4๏ธโƒฃ Deleting a File (os.remove())

os.remove("new_example.txt")
print("File deleted!")

โš  Be careful! This action is irreversible.


๐Ÿ”น 5๏ธโƒฃ Getting File Size (os.path.getsize())

file_path = "data.txt"

if os.path.exists(file_path):
    size = os.path.getsize(file_path)
    print(f"File size: {size} bytes")
else:
    print("File not found!")

โœ… Use Case: Check file size before uploading.


๐Ÿ”น 6๏ธโƒฃ Checking If It’s a File or Directory (os.path.isfile() & os.path.isdir())

path = "example.txt"

if os.path.isfile(path):
    print("It's a file!")
elif os.path.isdir(path):
    print("It's a directory!")
else:
    print("Path does not exist.")

โœ… Use Case: Prevent errors by verifying paths.


๐Ÿ”น 7๏ธโƒฃ Getting File Path Information

๐Ÿ”น Absolute Path (os.path.abspath())

print(os.path.abspath("example.txt"))

๐Ÿ”น File Name (os.path.basename())

print(os.path.basename("/home/user/example.txt"))  # Output: example.txt

๐Ÿ”น Directory Name (os.path.dirname())

print(os.path.dirname("/home/user/example.txt"))  # Output: /home/user

โœ… Use Case: Manage file locations in scripts.


๐Ÿ”น 8๏ธโƒฃ Listing All Files in a Directory (os.listdir())

print(os.listdir("."))  # Lists all files & folders in the current directory

โœ… Use Case: Scan directories for specific files.


๐Ÿ”น 9๏ธโƒฃ Creating and Removing Directories

๐Ÿ”น Create a Directory (os.mkdir())

os.mkdir("new_folder")
print("Directory created!")

๐Ÿ”น Remove an Empty Directory (os.rmdir())

os.rmdir("new_folder")
print("Directory removed!")

โœ… Use Case: Organizing files dynamically.


๐Ÿ”น ๐Ÿ”Ÿ Removing a Directory with Files (shutil.rmtree())

If a directory contains files, use the shutil module.

import shutil
shutil.rmtree("folder_with_files")
print("Directory and all contents deleted!")

โœ… Use Case: Clean up unwanted folders.


๐Ÿ”น Summary Table

Function Purpose
os.path.exists(path) Check if a file or directory exists.
os.rename(old, new) Rename a file or directory.
os.remove(path) Delete a file.
os.path.getsize(path) Get file size in bytes.
os.path.isfile(path) Check if a path is a file.
os.path.isdir(path) Check if a path is a directory.
os.listdir(path) List files and directories.
os.mkdir(path) Create a new directory.
os.rmdir(path) Remove an empty directory.
shutil.rmtree(path) Delete a directory with all its contents.

Would you like real-world examples, like automating file backups? ๐Ÿš€


Leave a Reply

Your email address will not be published. Required fields are marked *