Explain Codes LogoExplain Codes Logo

How do I move a file in Python?

python
file-handling
pathlib
file-movement
Nikita BarsukovbyNikita Barsukov·Sep 22, 2024
TLDR

Shift a file swiftly using shutil.move() from the Python's in-built shutil library. Example:

import shutil # Move it like you stole it. Just kidding folks, we're totally legit. shutil.move('source_file.txt', 'destination_folder/')

The above piece of code moves source_file.txt from the source to destination_folder. Validate your paths for smooth movement.

File moving: choosing the right path

When you decide to move files around in Python, let's dig deeper to understand the crucial distinctions between the various methods available.

Tools for moving: picking the right one

shutil.move() is often the first choice due to its versatility. However, the os module provides os.rename() and os.replace() which have their own use-cases:

  • os.rename() is ideal for when shifting file to a new location within the same filesystem. It might throw tantrums otherwise.
  • os.replace() is similar to os.rename() but it has a special power. On Windows, it smoothly overwrites the destination file unlike its picky cousin os.rename().

Destination check: preparing for arrival

Before the actual move, ensure your destination directory is ready and existing. Meet pathlib—an object-oriented approach to handle filesystem paths:

from pathlib import Path /* Knock knock! Is anyone home? */ Path('destination_folder/').mkdir(parents=True, exist_ok=True)

Cross-filesystem moves and shutil.move(): the hidden performance cost

An important detail: shutil.move() could potentially perform a copy and delete operation when moving files across different filesystems. This can slow things down a little and will require temporary extra space.

Pathnames and filenames: the inseparable duo

Always include the filename in your destination path to retain the file's name after the move:

# Don't leave your filename behind! It's like leaving a child at the mall. shutil.move('source_folder/source_file.txt', 'destination_folder/source_file.txt')

Advanced Python wizardry for moving files

Now that you have the basics down, it's time for the big leagues. Let's dive into advanced techniques for handling more complex tasks:

Moving file types or selective attention

To pick files of a specific type to move, we combine os.listdir() with fnmatch.filter:

import fnmatch import os # It's '.txt' time to shine. for file in fnmatch.filter(os.listdir('source_folder'), '*.txt'): # 'You're going to a new home, txt files!' shutil.move(os.path.join('source_folder', file), 'destination_folder/')

Custom file handling with loops

With iteration, we can apply custom logic (like sorting or filtering) before the move:

# The Sorting Hat decides your house... I meant, folder. for file in sorted(os.listdir('source_folder')): # Custom Gryffin... file handling magic here shutil.move(os.path.join('source_folder', file), 'destination_folder/')

Moving on up: pathlib enters the scene

pathlib simplifies many file operations. Without further ado:

from pathlib import Path src = Path('source_file.txt') dst = Path('destination_folder/') # 'I put a spell on you and now you're moved!' src.rename(dst / src.name)

Thanks to pathlib, dealing with filesystem paths is now a breeze and the code is more human-readable.