Move a file to an archive folder with shutil.move in Python

Move a file to an archive folder with shutil.move, creating the folder if needed, and return the new path.

Easy Python 3.9+ Aug 9, 2026 Files & data 12 views 0 copies

Python code

20 lines
Python 3.9+
from pathlib import Path
import shutil

def move_file_to_archive(source_file: str, archive_folder: str) -> Path:
    """Move a file to the archive folder, creating it if needed."""
    src = Path(source_file)
    archive = Path(archive_folder)
    archive.mkdir(parents=True, exist_ok=True)
    destination = archive / src.name
    moved_file = shutil.move(str(src), str(destination))
    return Path(moved_file)

if __name__ == "__main__":
    # Create a test file and move it to archive
    test_file = Path("data.txt")
    test_file.write_text("Important data\n")
    result = move_file_to_archive("data.txt", "archive")
    print(f"Moved to: {result}")
    print(f"Exists in archive: {result.exists()}")
    print(f"Original exists: {test_file.exists()}")

Output

stdout
Moved to: archive/data.txt
Exists in archive: True
Original exists: False

How it works

The Path class from pathlib builds cross-platform paths. archive.mkdir(parents=True, exist_ok=True) creates the archive folder if it does not exist, without errors if it already does. shutil.move moves the file, handling both files and directories, and returns the new location. Avoiding name collisions is up to you; this simple version overwrites if a file with the same name exists.

Common mistakes

  • Forgetting `parents=True` so nested archive paths fail if they do not exist
  • Using `os.rename` instead of `shutil.move` which works only within the same filesystem
  • Not using `exist_ok=True` causes a `FileExistsError` when the folder already exists
  • Ignoring the returned path from `shutil.move` assuming it always matches the intended destination

Variations

  1. Use `os.makedirs(archive_folder, exist_ok=True)` with `os.rename` for simple same-filesystem moves
  2. Use `shutil.copy2` followed by `src.unlink()` if you need to copy metadata explicitly

Real-world use cases

  • Archiving processed log files into a dated folder after daily batch processing.
  • Moving uploaded files to a permanent storage folder after validation.
  • Relocating temporary download files to an archive when a job completes.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.