0
0
PythonHow-ToBeginner · 3 min read

How to Move a File in Python: Simple Guide with Examples

To move a file in Python, use the shutil.move(src, dst) function from the shutil module, where src is the source file path and dst is the destination path. This function moves the file and can also rename it if needed.
📐

Syntax

The basic syntax to move a file in Python is:

  • shutil.move(src, dst): Moves the file from src (source path) to dst (destination path).
  • src: The path of the file you want to move.
  • dst: The path where you want to move the file. It can be a directory or a new file name.

This function is part of the shutil module, so you need to import it first.

python
import shutil

shutil.move('source_path/file.txt', 'destination_path/file.txt')
💻

Example

This example shows how to move a file named example.txt from the current folder to a folder named backup. If the backup folder does not exist, the code will create it first.

python
import shutil
import os

source = 'example.txt'
destination_folder = 'backup'
destination = os.path.join(destination_folder, 'example.txt')

# Create destination folder if it doesn't exist
if not os.path.exists(destination_folder):
    os.makedirs(destination_folder)

# Move the file
shutil.move(source, destination)

print(f"Moved '{source}' to '{destination}'")
Output
Moved 'example.txt' to 'backup/example.txt'
⚠️

Common Pitfalls

  • FileNotFoundError: Happens if the source file does not exist. Always check the file path before moving.
  • Destination folder missing: If the destination folder does not exist, shutil.move will raise an error. Create the folder first.
  • Overwriting files: If a file with the same name exists at the destination, it will be overwritten without warning.

Example of a common mistake and the correct way:

python
# Wrong: Moving file to a non-existing folder
import shutil

# This will raise an error if 'new_folder' does not exist
# shutil.move('file.txt', 'new_folder/file.txt')

# Correct: Create folder first
import os

if not os.path.exists('new_folder'):
    os.makedirs('new_folder')
shutil.move('file.txt', 'new_folder/file.txt')
📊

Quick Reference

Here is a quick summary of moving files in Python:

ActionCode ExampleNotes
Import moduleimport shutilRequired to use move function
Move fileshutil.move('src.txt', 'dst.txt')Moves and can rename file
Create folderos.makedirs('folder')Create destination folder if missing
Check file existsos.path.exists('file.txt')Avoid FileNotFoundError
Overwrite warningNoneExisting files at destination are overwritten

Key Takeaways

Use shutil.move(src, dst) to move or rename files in Python.
Always import shutil before using move.
Create the destination folder before moving files to avoid errors.
Check if the source file exists to prevent FileNotFoundError.
Moving a file will overwrite existing files at the destination without warning.