How to move a file from one folder to another using Python?

The Python shutil module provides functions for high-level file operations. Python offers several methods to move files between directories, each with different advantages.

Using shutil.move() Method

The shutil.move() function moves files or directories from source to destination. It can handle both files and directories automatically ?

import shutil
import os

# Moving a single file
shutil.move('source_file.txt', 'destination_folder/')
print("File moved successfully")
File moved successfully

Moving Multiple Files

import shutil
import os

# Create sample files for demonstration
with open('file1.txt', 'w') as f:
    f.write("Sample file 1")
with open('file2.txt', 'w') as f:
    f.write("Sample file 2")

os.makedirs('destination', exist_ok=True)

# Get all .txt files
origin = './'
target = './destination/'

files = [f for f in os.listdir(origin) if f.endswith('.txt')]

for file in files:
    shutil.move(os.path.join(origin, file), target)
    print(f"Moved: {file}")
Moved: file1.txt
Moved: file2.txt

Using os.rename() Method

The os.rename() method moves files by renaming their path. It works by changing the file's directory location ?

import os

# Create a sample file
with open('sample.txt', 'w') as f:
    f.write("Sample content")

os.makedirs('target_folder', exist_ok=True)

# Move file using os.rename()
os.rename('sample.txt', 'target_folder/sample.txt')
print("File moved using os.rename()")
File moved using os.rename()

Using Pathlib Module

The pathlib module provides an object-oriented approach to file operations. It offers a more modern and readable way to handle file paths ?

from pathlib import Path
import shutil

# Create sample files
Path('source_dir').mkdir(exist_ok=True)
Path('dest_dir').mkdir(exist_ok=True)

sample_file = Path('source_dir/test.txt')
sample_file.write_text("Test content")

# Move using pathlib
destination = Path('dest_dir/test.txt')
shutil.move(str(sample_file), str(destination))
print(f"Moved {sample_file.name} to {destination.parent}")
Moved test.txt to dest_dir

Pattern-Based Moving with Pathlib

from pathlib import Path
import shutil

# Create sample files
source_dir = Path('source')
dest_dir = Path('destination')

source_dir.mkdir(exist_ok=True)
dest_dir.mkdir(exist_ok=True)

# Create multiple Python files
for i in range(3):
    (source_dir / f'script{i}.py').write_text(f"# Script {i}")

# Move all .py files
for py_file in source_dir.glob('*.py'):
    shutil.move(str(py_file), str(dest_dir))
    print(f"Moved: {py_file.name}")
Moved: script0.py
Moved: script1.py
Moved: script2.py

Comparison of Methods

Method Cross-Platform Handles Directories Best For
shutil.move() Yes Yes General file moving
os.rename() Yes Yes Simple rename/move operations
pathlib Yes Yes (with shutil) Modern, readable code

Error Handling

import shutil
import os

def safe_move(source, destination):
    try:
        if os.path.exists(source):
            shutil.move(source, destination)
            print(f"Successfully moved {source} to {destination}")
        else:
            print(f"Source file {source} does not exist")
    except FileNotFoundError:
        print("File not found")
    except PermissionError:
        print("Permission denied")
    except Exception as e:
        print(f"Error: {e}")

# Example usage
safe_move('nonexistent.txt', 'destination/')
Source file nonexistent.txt does not exist

Conclusion

Use shutil.move() for reliable cross-platform file moving. Choose pathlib for modern, readable code when working with complex path operations. Always include error handling for robust file operations.

Updated on: 2026-03-24T18:32:34+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements