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