File Organizing with Python: Rename, Move, Copy & Delete Files and Folders

File Organizing with Python: Rename, Move, Copy & Delete Files and Folders

Learn how to automate file organization in Python

Featured on daily.dev

Python is the perfect tool to automate file organization. In this article you will learn how to use Python to rename, move, copy, and delete files and folders.

I also included an example script that cleans up your Desktop.

If you prefer a video, you can watch the tutorial here:

How to navigate and change the directory in Python

You can use os.getcwd() to get the current working directory, and os.chdir() to change into another directory:

import os

print(os.getcwd())

os.chdir("/Users/patrick/Desktop/video-files")

print(os.getcwd())
# /Users/patrick/Desktop/video-files

How to rename files in Python

You can use os.rename() or pathlib.Path.rename().

This example changes filenames from

  • 'dictionary - python-course-3.mov'

to -->

  • '03-python-course-dictionary.mov'
import os

for file in os.listdir():
    # split into base name and extension
    name, ext = os.path.splitext(file)

    splitted = name.split("-")
    splitted = [s.strip() for s in splitted]
    new_name = f"{splitted[3].zfill(2)}-{splitted[1]}-{splitted[2]}-{splitted[0]}{ext}"

    os.rename(file, new_name)

Or as modern alternative you can usepathlib.Path:

import os
from pathlib import Path

for file in os.listdir():
    f = Path(file)

    # split into base name and extension
    name, ext = f.stem, f.suffix

    splitted = name.split("-")
    splitted = [s.strip() for s in splitted]
    new_name = f"{splitted[3].zfill(2)}-{splitted[1]}-{splitted[2]}-{splitted[0]}{ext}"

    f.rename(new_name)

How to create directories:

You can use pathlib.Path.mkdir() or os.mkdir():

from pathlib import Path
Path("data").mkdir(exist_ok=True)

# or
import os
if not os.path.exists("data"):
    os.mkdir("data")

How to move files in Python

This can be done with the shutil module:

import shutil

shutil.move('source', 'destination')  # works for file and folder

How to copy files in Python

This can be done with shutil.copy() or shutil.copy2(). The latter also copies all metadata:

import shutil

shutil.copy('source', 'destination')  # new metatags
shutil.copy2('source', 'destination')  # copies metadata, too

How to delete files and folders in Python

For files we can use os.remove() and for empty folders os.rmdir(). To recursively delete non-empty folders we can use shutil.rmtree():

os.remove("filename")  # error if not found
os.rmdir("folder")  # error if not empty, or not found
shutil.rmtree("folder")  # works for non empty directories

Organize and clean up your Desktop with Python

This example script can be used to move images, videos, screenshots, and audio files into corresponding folders.

A great way to run this script automatically is by using a cron job. In this article you can learn how to schedule Python scripts as cron jobs with crontab (Mac/Linux).

import os
import shutil


audio = (".3ga", ".aac", ".ac3", ".aif", ".aiff",
         ".alac", ".amr", ".ape", ".au", ".dss",
         ".flac", ".flv", ".m4a", ".m4b", ".m4p",
         ".mp3", ".mpga", ".ogg", ".oga", ".mogg",
         ".opus", ".qcp", ".tta", ".voc", ".wav",
         ".wma", ".wv")

video = (".webm", ".MTS", ".M2TS", ".TS", ".mov",
         ".mp4", ".m4p", ".m4v", ".mxf")

img = (".jpg", ".jpeg", ".jfif", ".pjpeg", ".pjp", ".png",
       ".gif", ".webp", ".svg", ".apng", ".avif")

def is_audio(file):
    return os.path.splitext(file)[1] in audio

def is_video(file):
    return os.path.splitext(file)[1] in video

def is_image(file):
    return os.path.splitext(file)[1] in img

def is_screenshot(file):
    name, ext = os.path.splitext(file)
    return (ext in img) and "screenshot" in name.lower()

os.chdir("/Users/patrick/Desktop")

for file in os.listdir():
    if is_audio(file):
        shutil.move(file, "Users/patrick/Documents/audio")
    elif is_video(file):
        shutil.move(file, "Users/patrick/Documents/video")
    elif is_image(file):
        if is_screenshot(file):
            shutil.move(file, "Users/patrick/Documents/screenshots")
        else:
            shutil.move(file, "Users/patrick/Documents/images")
    else:
        shutil.move(file, "Users/patrick/Documents")