Python File Automation: Copy, Move, Delete
Automate file system tasks efficiently using Python’s os
and shutil
modules.
Setup & Basics
- Import modules:
import os
,import shutil
- Current working directory:
os.getcwd()
- Change directory:
os.chdir('path/to/dir')
File Operations
-
Copy a file:
1 2
shutil.copy('source.txt', 'destination.txt') # Destination can be a new name or existing directory
-
Move/Rename a file:
1 2
shutil.move('old_name.txt', 'new_location/new_name.txt') # Renames if new_location is same as old
-
Delete a file:
1
os.remove('file_to_delete.txt')
Directory Operations
-
Create a directory:
1 2 3 4
os.mkdir('new_folder') # Creates single directory os.makedirs('path/to/new/nested/folder') # Creates all intermediate directories
-
List directory contents:
1 2
os.listdir('.') # Returns list of names
-
Delete an empty directory:
1
os.rmdir('empty_folder')
-
Delete non-empty directory (CAUTION!):
1 2
shutil.rmtree('folder_with_content') # Recursively deletes directory and all contents
Path Management
- Use
os.path.join()
for OS-agnostic path construction. - Example:
file_path = os.path.join('data', 'reports', 'report.pdf')
This post is licensed under CC BY 4.0 by the author.