Como usar o pathlib path facilmente?
Python’s pathlib Module: Taming the File System
Working with files and interacting with the file system are common tasks for Python developers. Some cases may involve only reading or writing files, but sometimes more complex tasks are at hand. Maybe you need to list all files of a given type in a directory, find the parent directory of a given file, or create a unique filename that doesn’t already exist. That’s where pathlib
comes in.
The pathlib
module is part of Python’s standard library, and it helps you deal with all those challenges. It gathers the necessary functionality in one place and makes it available through methods and properties on a convenient Path
object.
In this tutorial, you’ll learn how to:
- Work with file and directory paths in Python.
- Instantiate a
Path
object in different ways. - Use
pathlib
to read and write files. - Carefully copy, move, and delete files.
- Manipulate paths and the underlying file system.
- Pick out components of a path.
You’ll also explore a bunch of code examples in this tutorial, which you can use for your everyday file operations. For example, you’ll dive into counting files, finding the most recently modified file in a directory, and creating unique filenames.
The Problem With Representing Paths as Strings
With Python’s pathlib
, you can save yourself some headaches. Its flexible Path
class paves the way for intuitive semantics. Before you have a closer look at the class, take a moment to see how Python developers had to deal with paths before pathlib
was around.
Traditionally, Python has represented file paths using regular text strings. However, since paths are more than plain strings, important functionality was spread all around the standard library, including in libraries like os
, glob
, and shutil
.
As an example, the following code block moves files into a subfolder:
You need three import statements in order to move all the text files to an archive directory. This approach can quickly become cumbersome and hard to read, especially when dealing with more complex path operations.
Path Instantiation With Python’s pathlib
The first step to start using pathlib
is to instantiate a Path
object. There are different ways to do this. Let’s explore them:
Using Path Methods
pathlib
provides a Path()
method that allows you to create a Path
object. This method can take multiple arguments, each representing a part of the path. For example, to create a Path
object representing the file example.txt
in the current directory, you can use the following code:
In this case, the argument passed to the Path()
method is a string representing the file name. You can also pass multiple arguments to represent a more complex path structure, like directories and subdirectories.
Passing in a String
Another way to create a Path
object is by passing in a string representing the path. The Path()
method can directly accept a string as its argument. For example:
Here, the string "path/to/example.txt"
represents the file example.txt
located in the path/to
directory.
Joining Paths
One of the advantages of pathlib
is the ability to easily join multiple path elements together. This is done using the /
operator. For example, you can join two paths like this:
In this case, the resulting path
object represents the file example.txt
located in the path/to
directory.
File System Operations With Paths
Once you have a Path
object representing a file or directory, you can perform various file system operations on it. pathlib
provides methods and properties to help you accomplish these tasks. Let’s explore some of them:
Picking Out Components of a Path
The Path
object provides properties that allow you to access different parts of the path. For example, you can use the name
property to get the name of the file or directory represented by the Path
object:
Similarly, you can use the parent
property to get the parent directory of the file or directory:
Reading and Writing Files
pathlib
provides methods for reading and writing files. The read_text()
method allows you to read the contents of a file as a string:
To write to a file, you can use the write_text()
method:
Renaming Files
To rename a file, you can use the rename()
method of the Path
object. Here’s an example:
Copying Files
To copy a file, you can use the copy()
method. It creates a new file with the same contents as the original file. Here’s an example:
Moving and Deleting Files
To move a file to a different directory or rename it, you can use the replace()
method. It takes a new path as its argument. Here’s an example:
To delete a file, you can use the unlink()
method:
Creating Empty Files
To create an empty file, you can use the touch()
method:
Python pathlib Examples
Now that you have an understanding of the basic concepts of pathlib
, let’s explore some practical examples:
Counting Files
You can use pathlib
to count the number of files in a directory:
This code snippet counts the number of files in the path/to/directory
directory and displays the result.
Displaying a Directory Tree
pathlib
allows you to create a tree-like representation of a directory and all its subdirectories:
This code snippet displays a tree-like representation of the path/to/directory
directory and all its subdirectories.
Finding the Most Recently Modified File
You can use pathlib
to find the most recently modified file in a directory:
This code snippet finds the most recently modified file in the path/to/directory
directory and displays its name.
Creating a Unique Filename
If you need to create a new file with a unique name, you can use pathlib
to generate a unique filename:
This code snippet generates a unique filename using the uuid
module and creates a new file with that name in the path/to/directory
directory.
Conclusion
In this tutorial, you’ve learned how to use Python’s pathlib
module to work with file and directory paths. You’ve seen how to instantiate a Path
object, perform file system operations on paths, and manipulate paths and the underlying file system. You’ve also explored several code examples that demonstrate practical use cases of pathlib
.
pathlib
provides a powerful and intuitive way to work with paths in Python, making it easier to handle file and directory operations in your code. With the knowledge you’ve gained, you’ll be able to tame the file system and efficiently work with files and directories in your Python projects.