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.