Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Moving and Deleting Files

00:00 Moving and Deleting Files. Through pathlib, you also have access to basic file system level operations like moving, updating, and even deleting files. For the most part, these methods do not give a warning or wait for confirmation before information or files are lost, so you need to be careful when using these methods.

00:22 To move a file, use .replace(). Note that if the destination already exists, .replace() will overwrite it. Unfortunately, pathlib does not explicitly support safe moving of files.

00:36 To avoid possibly overwriting the destination path, the simplest route is to test whether the destination exists before replacing it. However, this does leave the door open for a possible race condition.

00:48 Another process may add a file at the destination path between the execution of the if statement and the .replace() method.

00:57 If that’s a concern, a safer way is to open the destination path for exclusive creation and explicitly copy the source data, as seen on-screen. This code will raise a FileExistsError if the destination already exists.

01:12 Technically, this copies a file. To perform a move, delete the source file after the copy is done, but make sure no exception was raised before you do this.

01:24 When you’re renaming files, iseful methods might be .with_name() and .with_suffix(). They both return the original path, but with the name or the suffix replaced, respectively.

01:38 You can see this in action on-screen.

02:04 Directories and files can be deleted using .rmdir() and .unlink(), respectively. But again, you need to ensure that you are doing this with appropriate care and consideration. In the next section of the course, you’ll see how easy pathlib makes it to select specific components of a path.

Become a Member to join the conversation.