HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

12) Modules and Automation Lesson

Move Files: Python Replace

13 min to complete · By Martin Breuss

You've found your way to your Desktop and you peeked at all the files there. As of now, you're still only dreaming of a clean Desktop.

Revisit your Pseudocode

You've already tackled a couple of the tasks you noted down in pseudocode when you began to work on this challenge. Time to take another look at them:

# Import pathlib
import pathlib

# Find the path to my Desktop
desktop = pathlib.Path('/Users/martin/Desktop')

# List all the files on there
for filepath in desktop.iterdir():
    print(filepath.name)

# Filter for screenshots only
# Create a new folder
# Move the screenshots in there

Filter Files with Python Suffix

Three tasks are done, and three more to go! Next, you'll filter all the files so you can pick out only the screenshots. You can do this with another attribute to a pathlib.Path object called .suffix.

Filter by File Extension

On my system, screenshots have the file extension .png. Python's pathlib module is aware of the file extensions of the paths it's working with. In the same way that you were able to get just the .name of a pathlib.Path object, you can also just get its .suffix instead:

import pathlib

desktop = pathlib.Path('/Users/martin/Desktop')

for filepath in desktop.iterdir():
    print(filepath.suffix)

This code prints out all the file extensions instead of the names of the files on your Desktop. But you want to filter and only do something to the files with a .png extension. Sounds like a job for a conditional statement:

import pathlib

desktop = pathlib.Path('/Users/martin/Desktop')

for filepath in desktop.iterdir():
    if filepath.suffix == '.png':  # Filter for screenshots only
        print(filepath.name)

By adding the conditional statement, you're telling Python to only address the files that have .png as their file extension. These are your screenshots. Now you need a new place where to move them to.

Python Mkdir

The pathlib module comes with many convenient abstractions that make interacting with your file system easier. Many of the methods resemble commands you might remember from working with Bash.

Python Create Directory

For example, if you want to create a new directory in Bash, you use the mkdir command. You can do the same with Python's pathlib:

import pathlib

new_path = pathlib.Path('/Users/martin/Desktop/screenshots')
new_path.mkdir()

Calling .mkdir() on a pathlib.Path object will try to create a new directory at the path that it's pointing to. In this case, that's a folder called screenshots on my Desktop. If the folder already exists, this operation will fail with an aptly named FileExistsError.

You can circumvent this error by passing an argument called exist_ok with the value True when calling .mkdir():

import pathlib

new_path = pathlib.Path('/Users/martin/Desktop/screenshots')
new_path.mkdir(exist_ok=True)

Check if Directory Exists

If you add exist_ok=True, the directory will get created if it doesn't already exist. If it exists, then the code will pass and continue. You can add this to your code:

# Import pathlib
import pathlib

# Find the path to my Desktop
desktop = pathlib.Path('/Users/martin/Desktop')
# Create a new folder
new_path = pathlib.Path('/Users/martin/Desktop/screenshots')
new_path.mkdir(exist_ok=True)

for filepath in desktop.iterdir():
    # Filter for screenshots only
    if filepath.suffix == '.png':
        print(filepath.name)

# Move the screenshots in there

You've updated the order of your pseudocode a bit by moving the creation of the new folder above the for loop that iterates over the files on your Desktop. You also removed the comment about listing all files because it wasn't relevant anymore.

Colorful illustration of a light bulb

Info: Changing and updating your pseudocode, as well as your actual code, while developing your program is completely normal. You'll never think of everything you need to do, or in what order, quite correctly. Pseudocode is there to give you a scaffolding to get started, and you can change and update it at any time as it best fits.

At this point, there's only one last piece of functionality missing. You need to actually move the screenshots into the new folder.

Python Replace

The final piece of the puzzle is to move the files from the Desktop into the new screenshots directory. The method to do this is called .replace() and it works like so:

oldpath.replace(newpath)

For this to work correctly, oldpath needs to point to a pathlib.Path object, and newpath needs to be a valid path string or another pathlib.Path object.

Colorful illustration of a light bulb

Note: As the documentation tries to warn you if the target points to an existing file or directory, it will be unconditionally replaced. Keep that in mind to avoid overwriting existing files on your computer!

Move Files in Python

In your Desktop-cleaning example, you'll want to move all screenshots that are currently on your Desktop into the new and empty screenshots folder. This means that you'll want to construct a new file path for each file that points inside that new folder and keeps the original filename:

# Import pathlib
import pathlib

# Find the path to my Desktop
desktop = pathlib.Path('/Users/martin/Desktop')
# Create a new folder
new_path = pathlib.Path('/Users/martin/Desktop/screenshots')
new_path.mkdir(exist_ok=True)

for filepath in desktop.iterdir():
    # Filter for screenshots only
    if filepath.suffix == '.png':
        # Create a new path for each file
        new_filepath = new_path.joinpath(filepath.name)
        # Move the screenshot there
        filepath.replace(new_filepath)

There are three things you've introduced in the final two lines of code:

        # Create a new path for each file
        new_filepath = new_path.joinpath(filepath.name)
        # Move the screenshot there
        filepath.replace(new_filepath)

Disect the Code

Time to pick it apart.

First Line

beginning with the first new line of code:

  • new_filepath is the variable name you're assigning the new file path to.
  • new_path is the path to the new folder called screenshots that you created on your Desktop.
  • .joinpath() is a method that allows you to combine the paths of multiple pathlib.Path objects. In this case, that'll be new_path and what you'll pass as an argument in between the parentheses.
  • filepath.name is the filename of each screenshot.

In this line, you're creating a new file path that points to where you want the screenshot to move. You're constructing it from the path of the new folder you created and the filename of the existing file.

Colorful illustration of a light bulb

Info: There's quite a bit going on in just two lines of code. This is the power of abstraction and why using modules can make building functionality quick and not require lots of code. Don't worry if you don't understand a lot of what's going on behind the scenes; this is also partly what abstraction means. You'll keep stripping off more and more layers as you progress in this course.

Second Line

In the second line of code, you're finally moving the screenshots to their new location:

  • filepath is the name for the iterator in your for loop. As you confirmed in the last lesson, this will be the absolute path of each file with the .png suffix.
  • .replace() is the method you are calling on the pathlib.Path object called filepath. It will replace the old path, filepath, with the new one that you'll pass as an argument in between the parentheses.
  • new_filepath is the variable that you created in the previous line of code. It points to the new path where you want to move the screenshot to.

Because these operations are inside of your for loop and use the filepath iterator variable, they'll get applied to each screenshot that is currently on your Desktop.

After you save and run this script, you're Desktop will be released of its screenshot burden:

Clean Desktop with CodingNomads logo as background image

Ah! Fresh air! You've just written a Python script that automated tasks on your computer's file system. Nice work!

Summary: Moving Files Python Replace

  • Filter files for a specific file extension with .suffix
  • Create a new folder using .mkdir() on a new pathlib.Path object
  • Move files from one location to another using .replace()
  • Files can be overwritten with replace, so be careful when applying this method to your files