How do I move a file in Python?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Moving files is a routine operation in Python scripts, from log rotation to ETL pipelines and deployment tooling. The code is simple, but production behavior depends on filesystem boundaries, overwrite rules, and error handling. The safest default is to use shutil.move with explicit checks and clear failure paths.
Choose the Right API
Python gives you two common options:
os.renamefor simple same-filesystem renames or moves.shutil.movefor general-purpose moves, including cross-filesystem cases.
os.rename is fast and direct, but it can fail when source and destination are on different mounts. shutil.move handles that by falling back to copy-then-delete behavior when needed.
Basic Move With shutil.move
Use pathlib for readable path code and shutil.move for the operation.
This covers most script needs and works on Linux, macOS, and Windows.
Preserve Safety With Pre-Checks
Moving files in automation should include checks for existence and destination collisions.
This pattern avoids silent clobbering and makes behavior explicit.
Moving Into a Directory
If destination path is a directory, shutil.move keeps the original filename.
This is useful for bulk archival jobs where filename stays unchanged.
Cross-Filesystem Behavior
On same filesystem, move can be a metadata rename operation. Across filesystems, Python typically copies bytes then removes source file. That can be slower and can fail midway due to permissions or disk space.
If atomic behavior is required, keep source and destination on same filesystem and use rename semantics. For critical workloads, log each move and verify destination hash before deleting source when implementing custom copy workflows.
Error Handling You Actually Need
Catch expected exceptions and include contextual logs.
In data pipelines, return status values and aggregate failures for retry instead of crashing the first time.
Batch Moves
For many files, iterate with deterministic filtering and explicit destination mapping.
Keep naming collisions in mind for batch jobs that run repeatedly.
Common Pitfalls
A common pitfall is using os.rename assuming it always works across disks, then failing in container or network-mounted environments. Another issue is moving files without creating destination directories first. Teams also forget collision handling and overwrite files unexpectedly. Passing Path objects to older utility wrappers that expect strings can create subtle compatibility issues in mixed codebases. Finally, batch move scripts often ignore partial failures, which leads to hard-to-debug data gaps when some files moved and others did not.
Summary
- Use
shutil.moveas the default for reliable file moves in Python. - Use
os.renamewhen you specifically need same-filesystem rename behavior. - Add pre-checks for source existence and destination collisions.
- Create destination directories explicitly before move operations.
- Treat batch moves as operational workflows with logging, retries, and failure reporting.
Related reading
- How do I override __getattr__ without breaking the default behavior?
- How do I parallelize a simple Python loop?
- How do I pass a method as a parameter in Python
- How do I pass a string into subprocess.Popen using the stdin argument?
- How do I pass an async function to a thread target in Python?
- How do I plot in real-time in a while loop?
- How do I prepend to a short python list?
- How do I prevent Conda from activating the base environment by default?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.