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

</>
Copy
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:

  1. We import the shutil module to use the shutil.move() function.
  2. Define the source variable as the name of the file we want to move (sample.txt).
  3. Define the destination variable as the target location where we want to move the file.
  4. Call shutil.move(source, destination) to move the file.
  5. 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

</>
Copy
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:

  1. Import the shutil module.
  2. Set source as the file to be moved (data.csv).
  3. Set destination as the target folder with a new filename (new_data.csv).
  4. Call shutil.move(source, destination) to move and rename the file in one step.
  5. 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

</>
Copy
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:

  1. Import shutil and os modules.
  2. Set source as the file we want to move (report.pdf).
  3. Set destination as the target folder and filename.
  4. Use a try-except block to handle errors.
  5. Handle FileNotFoundError if the file does not exist.
  6. Handle PermissionError if access is denied.
  7. 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:

  1. Use shutil.move() to move a file to another directory.
  2. You can rename a file while moving it by specifying a new filename in the destination path.
  3. Handle errors using a try-except block to avoid runtime crashes.

These techniques help ensure smooth file management in Python programs.