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.
Python code
20 linesfrom 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
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
- Use `os.makedirs(archive_folder, exist_ok=True)` with `os.rename` for simple same-filesystem moves
- 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
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.