Copying, Moving and Renaming Files Safely
shutil.copy2 copies a file, shutil.move and Path.rename move and rename one, and three habits keep a file-moving script safe, a backup copy, a check that the destination is free, and a dry run that shows the plan before anything moves.
Journeyman · Python · Updated
After this lesson you can
- Copy, move and rename files with shutil.copy2, shutil.move and Path.rename
- Make a file-moving script safe with a backup copy, a check that the destination is free, and a dry run first
Key takeaways
- shutil.copy2(source, destination) copies a file and keeps its dates, so the copy looks like the original.
- shutil.move(source, destination) moves a file into a folder or to a new name, and Path.rename(new_path) renames a file or moves it.
- A move or rename can replace a file that's already at the destination, so check destination.exists() first and skip that file.
- A dry run prints what the script would do and changes nothing. Plan the moves, read the plan, then make them.
- A file-tidying script never deletes. Path.unlink() deletes with no Recycle Bin or Trash, so leave it out of anything that touches files you care about.
A script that adds up prices can only get a number wrong. A script that moves files can lose a photo, or put one file on top of another with the same name. You'll copy, move and rename files whenever you automate a chore on your computer: backing up receipts, sorting a Downloads folder, renaming a batch of photos. This lesson shows the three tools Python gives you, and the three habits that keep a file-moving script from doing damage.
The example tidies a Downloads folder. Each program makes its own practice folder, such as practice-downloads, and works only there.
Copy first: shutil.copy2
The shutil module (read "shell utilities") does the jobs you'd otherwise do by dragging files around. shutil.copy2(source, destination) copies a file. When the destination is a folder, the copy goes inside it with the same name:
import shutil
from pathlib import Path
downloads = Path("practice-downloads")
downloads.mkdir(exist_ok=True)
receipt = downloads / "grocery-receipt.pdf"
receipt.write_text("Milk 3.49, Eggs 4.29")
backup = Path("practice-backup")
backup.mkdir(exist_ok=True)
shutil.copy2(receipt, backup)
print((backup / "grocery-receipt.pdf").read_text())
print(receipt.exists())
Milk 3.49, Eggs 4.29
True
The copy has the same contents, and the original is still where it was. shutil.copy() copies too, but the copy's "last modified" date becomes today; copy2 keeps the original's dates, so a backup sorts and searches like the files it protects. That's the first habit: before a script changes a folder you care about, copy what matters somewhere else.
Moving and renaming
shutil.move(source, destination) moves a file. Give it a folder and the file goes inside, keeping its name; give it a full path and the file arrives with that name. A Path can also rename itself: source.rename(new_path) gives the file its new name, or a new name in a new folder.
import shutil
from pathlib import Path
downloads = Path("practice-downloads")
photos = downloads / "Photos"
photos.mkdir(parents=True, exist_ok=True)
(downloads / "beach-day.jpg").touch()
(downloads / "IMG_0412.jpg").touch()
shutil.move(downloads / "beach-day.jpg", photos)
(downloads / "IMG_0412.jpg").rename(photos / "canyon-hike.jpg")
for photo in sorted(photos.glob("*.jpg")):
print(photo.name)
beach-day.jpg
canyon-hike.jpg
Both files left practice-downloads for Photos, and IMG_0412.jpg got a name that says what's in it. shutil.move also works when the destination is on another drive, such as a USB stick, where rename can't go.
When the name is already taken
Run that program a second time. It makes a new beach-day.jpg and tries to move it into Photos, which already has one, and on Windows Python stops:
shutil.Error: Destination path 'practice-downloads\Photos\beach-day.jpg' already exists
(A Mac shows the same message with / in the path.) Stopping is the lucky case. When the destination is a full path to a file that's already there, such as photos / "beach-day.jpg", shutil.move replaces that file without a word, and so does rename on a Mac: the photo that was there is gone. Python's documentation says so; what happens depends on the computer and on how you named the destination. A safe script doesn't leave that to chance. It checks exists() before every move and skips a file whose destination is taken:
import shutil
from pathlib import Path
def move_into(source, folder):
target = folder / source.name
if target.exists():
print(f"Skipped {source.name}: {folder.name} already has one")
return
folder.mkdir(parents=True, exist_ok=True)
shutil.move(source, target)
print(f"Moved {source.name} to {folder.name}")
downloads = Path("practice-downloads")
downloads.mkdir(exist_ok=True)
(downloads / "sunset.jpg").write_text("this week's sunset")
move_into(downloads / "sunset.jpg", downloads / "Photos")
(downloads / "sunset.jpg").write_text("last year's sunset")
move_into(downloads / "sunset.jpg", downloads / "Photos")
print((downloads / "Photos" / "sunset.jpg").read_text())
Moved sunset.jpg to Photos
Skipped sunset.jpg: Photos already has one
this week's sunset
The second sunset.jpg stays in practice-downloads for a person to look at, and the one in Photos is untouched. A script built this way is idempotent (read "eye-dem-POH-tent"): safe to run again, because a second run can't undo or damage the first.
A dry run: the plan before the moves
Before movers carry a single box, someone walks through the house with a clipboard and writes down which box goes to which room. You read the list, catch the mistake ("the piano goes downstairs"), and only then does anything move. A dry run is that clipboard: the script works out every move and prints it, and changes nothing.
import shutil
from pathlib import Path
downloads = Path("dry-run-downloads")
downloads.mkdir(exist_ok=True)
for name in ["beach-day.jpg", "grocery-receipt.pdf", "notes.txt"]:
(downloads / name).touch()
FOLDERS = {".jpg": "Photos", ".pdf": "Documents"}
dry_run = True
for file in sorted(downloads.iterdir()):
folder = FOLDERS.get(file.suffix)
if folder is None:
continue
if dry_run:
print(f"Would move {file.name} to {folder}")
else:
(downloads / folder).mkdir(exist_ok=True)
shutil.move(file, downloads / folder / file.name)
print(len(list(downloads.iterdir())), "files still in dry-run-downloads")
Would move beach-day.jpg to Photos
Would move grocery-receipt.pdf to Documents
3 files still in dry-run-downloads
notes.txt has no folder in FOLDERS, so it stays put. Read the plan; when it's right, set dry_run = False and run it again. The next lesson turns that line into a --dry-run option you type in the terminal.
The last habit is what this script leaves out. Python can delete a file with Path.unlink(), and a deleted file doesn't go to the Recycle Bin or the Trash: there's no undo. A tidying script moves and copies; it never deletes a file it found. The only files a script may delete are ones it made itself, such as a temporary file it no longer needs.
Do it: back up the receipts
Before the tidy-up script touches the Downloads folder, it backs up every receipt. Receipts are the .pdf files.
folder: the folder the receipts are in, as aPath.backup: the backup folder, as aPath. It may not exist yet.
Your job: write the function backup_receipts(folder, backup) so it copies each .pdf file in folder into backup and returns the names it copied.
- Make
backupif it isn't there yet. - Copy each
.pdffile withshutil.copy2, keeping its name. The originals stay infolder. - Skip a receipt whose name
backupalready has: leave that backup copy as it is, and don't count it. - Return the names of the files copied, sorted alphabetically. With nothing to copy, return
[].
Worked through: practice-downloads holds grocery-receipt.pdf, hardware-receipt.pdf and beach-day.jpg, and practice-backup already has hardware-receipt.pdf. Only grocery-receipt.pdf is copied, so backup_receipts(Path("practice-downloads"), Path("practice-backup")) returns ["grocery-receipt.pdf"].
Practiced live on the lesson page: write the Python right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
Copying first, checking before every move and printing the plan before making it are what let you point a script at a folder you care about and trust what it does.