DEV Community

Cover image for Build a Python File Mover
Jorddy
Jorddy

Posted on

Build a Python File Mover

Why should I try this mini task?

We are going to learn how to move many files using the magic of Python, taking advantage of iterations. This article explores a Python script that automatically moves all JPG files from your desktop to a new folder named "screenshots.".

Steps

  • Find your Desktop path: use pathlib to identify the location of your desktop folder. You can try any other folder in your computer!

Image description

  • Create a folder in your desktop to save all files in it: Check if the folder exists on your desktop. If not, it creates it using mkdir(exist_ok=True). This ensures the script doesn't encounter errors if the folder already exists.

Image description

  • Look for JPG files: Iterates through all files on your desktop using iterdir().. To move all JPG files, you need to look If a file ends with the ".JPG" extension.

for file_path in desktop_path.iterdir():
if file_path.suffix == ".JPG":

  • Move the files: Build a new path for the file within the new folder you just created. Finally, move the file to the new location using replace().

Image description

Just to check out, you can use print() to get a list of all files moved in the process.

This script provides a basic solution for organizing your desktop. You can adapt it to handle different file types or modify the destination folder name based on your needs.

Thank you for reading!
~jor

Top comments (0)