How to move and overwrite files and folders using Python?

Moving and overwriting files and folders is a common task in Python automation. Python provides the shutil and os modules to handle these operations efficiently.

Understanding shutil and os Modules

The shutil module provides high-level file operations like copying, moving, and removing files and directories. The os module offers operating system interface functions for file and directory management.

Moving Files

To move a file, use shutil.move() which handles both moving and renaming operations ?

import os
import shutil

# Create sample file for demonstration
os.makedirs('source_folder', exist_ok=True)
with open('source_folder/sample.txt', 'w') as f:
    f.write('Hello, World!')

# Move the file
src_file = 'source_folder/sample.txt'
dest_folder = 'destination_folder/'

# Create destination folder if it doesn't exist
os.makedirs(dest_folder, exist_ok=True)

# Move the file
shutil.move(src_file, dest_folder)
print("File moved successfully!")

# Check if file exists in destination
if os.path.exists('destination_folder/sample.txt'):
    print("File found in destination folder")
File moved successfully!
File found in destination folder

Moving and Overwriting Files

When moving files, shutil.move() automatically overwrites if the destination file already exists ?

import os
import shutil

# Create source and destination files
os.makedirs('source', exist_ok=True)
os.makedirs('dest', exist_ok=True)

with open('source/data.txt', 'w') as f:
    f.write('New content')

with open('dest/data.txt', 'w') as f:
    f.write('Old content')

print("Before move:")
with open('dest/data.txt', 'r') as f:
    print(f"Destination file content: {f.read()}")

# Move and overwrite
shutil.move('source/data.txt', 'dest/data.txt')

print("\nAfter move:")
with open('dest/data.txt', 'r') as f:
    print(f"Destination file content: {f.read()}")
Before move:
Destination file content: Old content

After move:
Destination file content: New content

Moving Folders

Use shutil.move() to move entire directories. If the destination exists, the source becomes a subdirectory ?

import os
import shutil

# Create source folder with content
os.makedirs('source_dir/subfolder', exist_ok=True)
with open('source_dir/file1.txt', 'w') as f:
    f.write('Content 1')
with open('source_dir/subfolder/file2.txt', 'w') as f:
    f.write('Content 2')

# Move the entire folder
shutil.move('source_dir', 'moved_directory')

print("Folder moved successfully!")
print("Contents of moved directory:")
for root, dirs, files in os.walk('moved_directory'):
    level = root.replace('moved_directory', '').count(os.sep)
    indent = ' ' * 2 * level
    print(f'{indent}{os.path.basename(root)}/')
    subindent = ' ' * 2 * (level + 1)
    for file in files:
        print(f'{subindent}{file}')
Folder moved successfully!
Contents of moved directory:
/
  file1.txt
  subfolder/
    file2.txt

Copying with Overwrite

For copying instead of moving, use shutil.copy() for files and shutil.copytree() for directories ?

import os
import shutil

# Create source content
os.makedirs('copy_source/data', exist_ok=True)
with open('copy_source/file.txt', 'w') as f:
    f.write('Source content')
with open('copy_source/data/info.txt', 'w') as f:
    f.write('Data file')

# Copy file (overwrites if exists)
shutil.copy('copy_source/file.txt', 'copied_file.txt')

# Copy directory tree (use dirs_exist_ok=True to overwrite)
shutil.copytree('copy_source', 'copy_destination', dirs_exist_ok=True)

print("Copy operations completed!")
print(f"Original still exists: {os.path.exists('copy_source/file.txt')}")
print(f"Copy created: {os.path.exists('copied_file.txt')}")
print(f"Directory copied: {os.path.exists('copy_destination/data/info.txt')}")
Copy operations completed!
Original still exists: True
Copy created: True
Directory copied: True

Comparison of Methods

Operation Function Behavior Original File
Move File shutil.move() Overwrites destination Removed
Copy File shutil.copy() Overwrites destination Preserved
Move Folder shutil.move() Creates subdirectory if dest exists Removed
Copy Folder shutil.copytree() Use dirs_exist_ok=True to overwrite Preserved

Conclusion

Use shutil.move() to move and automatically overwrite files and folders. For copying operations, use shutil.copy() and shutil.copytree() with appropriate parameters. Always handle exceptions when working with file operations in production code.

Updated on: 2026-03-27T15:23:16+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements