Move a File to Another Directory using Python
In Python, you can move a file from one directory to another using the shutil.move()
function from the shutil
module. This function takes the source file path and the destination directory or file path as arguments and moves the file accordingly.
Examples to Move a File
1. Moving a File to Another Directory
In this example, we will move a file named sample.txt
from the current working directory to a folder named destination_folder
.
Please note that the destination path must be a valid path. Otherwise, you would get FileNotFoundError.
main.py
import shutil
# Define source file path
source = "sample.txt"
# Define destination directory
destination = "destination_folder/sample.txt"
# Move the file
shutil.move(source, destination)
print("File moved successfully!")
Explanation:
- We import the
shutil
module to use theshutil.move()
function. - Define the
source
variable as the name of the file we want to move (sample.txt
). - Define the
destination
variable as the target location where we want to move the file. - Call
shutil.move(source, destination)
to move the file. - Print a success message once the file has been moved.
Output:
File moved successfully!
Output (if Destination is not valid):
Traceback (most recent call last):
File "/opt/homebrew/Cellar/python@3.13/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/shutil.py", line 856, in move
os.rename(src, real_dst)
~~~~~~~~~^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'sample.txt' -> 'destination_folder/sample.txt'
2. Moving a File and Renaming It
In this example, we will move the file data.csv
to another directory and rename it to new_data.csv
in the process.
main.py
import shutil
# Define source file path
source = "data.csv"
# Define destination directory with a new filename
destination = "backup/new_data.csv"
# Move and rename the file
shutil.move(source, destination)
print("File moved and renamed successfully!")
Explanation:
- Import the
shutil
module. - Set
source
as the file to be moved (data.csv
). - Set
destination
as the target folder with a new filename (new_data.csv
). - Call
shutil.move(source, destination)
to move and rename the file in one step. - Print a success message once the operation is complete.
Output:
File moved and renamed successfully!
3. Moving a File and Handling Errors
In this example, we will move a file while handling errors such as the file not existing or the destination folder being missing.
main.py
import shutil
import os
# Define source file path
source = "report.pdf"
# Define destination directory
destination = "archives/report.pdf"
try:
# Move the file
shutil.move(source, destination)
print("File moved successfully!")
except FileNotFoundError:
print("Error: The source file does not exist.")
except PermissionError:
print("Error: Permission denied.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Explanation:
- Import
shutil
andos
modules. - Set
source
as the file we want to move (report.pdf
). - Set
destination
as the target folder and filename. - Use a
try-except
block to handle errors. - Handle
FileNotFoundError
if the file does not exist. - Handle
PermissionError
if access is denied. - Print a general error message if any other unexpected error occurs.
Output (if file exists and moves successfully):
File moved successfully!
Output (if file does not exist):
Error: The source file does not exist.
Conclusion
Moving files in Python is simple with the shutil.move()
function. Here are the key takeaways:
- Use
shutil.move()
to move a file to another directory. - You can rename a file while moving it by specifying a new filename in the destination path.
- Handle errors using a
try-except
block to avoid runtime crashes.
These techniques help ensure smooth file management in Python programs.