Moving and Deleting Files
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: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.
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.
Directories and files can be deleted using
.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.