File & Directory Management, Automation, Copy/Move/Delete
os
and shutil
modulesshutil
When working on projects, you'll often need to:
Python's built-in os
and shutil
modules make these tasks simple and powerful.
os
Module – Working with Files and Directories
import os
print(os.getcwd()) # e.g., /Users/john/projects
files = os.listdir(".") # ".means current directory
print(files)
os.mkdir("new_folder") # create new folder
os.rmdir("new_folder") # remove empty folder
os.rename('old.txt', 'new.txt')
print(os.path.exists("data.txt")) # True/False
print(os.path.isfile("data.txt")) # Check if it's a file
print(os.path.isdir("my_folder")) # Check if it's a folder
shutil
Module – High-Level File OperationsThe shutil
module gives you advanced operations like copy, move, and delete.
import shutil
shutil.copy("data.txt", "backup.txt") # copy file
shutil.copytree("src_folder", "dest_folder") # copy entire folder
shutil.move("backup.txt", "archive/backup.txt")
shutil.rmtree("old_folder") # removes folder + all contents
⚠️ Be careful with rmtree()
– it deletes everything inside permanently.
import os, shutil
def organize_files(folder):
for filename in os.listdir(folder):
if filename.endswith(".txt"):
shutil.move(os.path.join(folder, filename), os.path.join(folder, "Text_Files", filename))
elif filename.endswith(".jpg"):
shutil.move(os.path.join(folder, filename), os.path.join(folder, "Images", filename))
organize_files("downloads")
This script organizes files in a folder into Text_Files and Images directories.
.pdf
files into PDFs/
.csv
files into CSVs/
.tmp
fileswith open(...)
when reading/writing filesos.path.join()
for cross-platform compatibilityshutil.rmtree()
as it deletes permanentlyModule | Feature | Example |
---|---|---|
os | Path handling, mkdir, listdir | os.listdir() |
shutil | Copy, move, delete directories | shutil.copy(), shutil.rmtree() |
Safety | Check before deleting/moving | os.path.exists("file.txt") |
Leave a Reply