How does Python pathlib work and what are its benefits?
The Python pathlib
module offers a very effective method for interacting with file system paths in the programming language. In addition to being easier to use, the module’s concise code is a major advantage.
What is Python pathlib
?
In the popular programming language Python, there are various methods for working with file system paths. Since version 3.4, for example, Python offers pathlib
, another very useful and comprehensive tool for interacting with paths independent of the operating system.
The module is particularly useful if you not only want to read or edit the paths, but also perform additional tasks and work steps. Among other things, it also allows you to create and copy individual files and their components. This is simplified above all by Python’s superordinate interface pathlib
. The module is part of the standard library and replaces or combines numerous other methods.
Object-oriented representation of paths
One of the key benefits of Python pathlib
is that it enables users to represent paths in an object-oriented manner, rather than as strings. The previous method was often cumbersome, requiring multiple statements for even simple tasks, but the new module’s syntax has been greatly simplified. Since you’ll typically be working with the Path class, it’s recommended to import it before starting any project. This will help streamline your code. To import, simply use the following command:
from pathlib import Path
pythonTo create a path
instance, you can already use Python pathlib
. The following code is suitable for this, where the two components “colors” and “blue.txt” are used. A new instance is then created with a simple command:
from pathlib import Path
blue = Path("colors", "blue.txt")
print(blue)
pythonThe output would then look like this, for example:
colors/blue.txt
pythonPython therefore places the operating system separator between the two components in the output. While this is a right slash /
in our example, the output on a computer with Windows can contain a backslash \
instead. For Linux and macOS, the slash is used.
How to call directories with Python pathlib
After you have imported Path
, you can use the various methods of the class with Python pathlib
. These include access to certain directories. For example, if you execute the following code, you call your current working directory:
from pathlib import Path
Path.cwd()
pythonThis is important, for example, if you want to open a file in the same directory in which your current script is being executed.
It is also possible to access the home directory of the current user with Python pathlib
. It is advisable to choose this directory as the starting point in order to be able to work with the corresponding paths on different computers if necessary. Here’s what the code looks like:
from pathlib import Path
Path.home()
pythonHow to use a string for access
Instead of starting with your working or home directory, it is still possible with Python pathlib
to access a file or directory using a string. For example, the corresponding code would look like this:
from pathlib import Path
Path(r"C:\Users\name\folder\file.txt")
pythonThe string is converted into a path and can therefore be used more easily. The small r
in front of the string identifies it as a “raw string literal”. This ensures that the backslash is actually used in this function. Otherwise, it can also be used to identify a non-printable variable.
How to join paths or strings
Another method of creating a new path with Python pathlib
is to connect individual paths or strings. You have two options for this.
By using a single slash, you connect two elements to form a new path. This could look like this, for example:
from pathlib import Path
for file_path in Path.cwd().glob("*.txt"):
new_path = Path("example") / file_path.name
file_path.rename(new_path)
pythonAlternatively, use the joinpath()
method and achieve the same result:
from pathlib import Path
Path.home().joinpath("example", "subfolder", "file.py")
pythonHow to use individual components
If you want to split a path into its components and use them, Python pathlib
also offers you the right tool for this. You will find some examples of this in the following code:
from pathlib import Path
path = Path(r"C:\Users\name\folder\file.txt")
path
path.anchor
path.name
path.parent
path.parent.parent
path.stem
path.suffix
python.anchor
: Refers to the portion preceding the actual directories; this can also differ based on the operating system.name
: Refers only to the file name without considering the directory.parent
: Refers to the directory containing the file; if the path points to a directory, it returns the parent directory.stem
: Refers to the file name excluding the extension.suffix
: Refers solely to the file extension
The corresponding expenses would then look like this:
'C:\\'
'file.txt'
WindowsPath('C:/Users/name/folder')
WindowsPath('C:/Users/name')
'file'
'.txt'
pythonHow to read or write files
Although it is also possible to write or read files by other means, you can use Python pathlib
to significantly shorten the code. To better illustrate how it works, let’s create a simple list containing animals and flowers. This is what it looks like:
<!-- exampleList.md -->
# ExampleList
## Animals
* Dog
* Cat
* Mouse
## Flowers
* Rose
* Carnation
textNow we use the standard function open()
with Python pathlib
to filter and output all animals and flowers from the list. The corresponding code looks like this:
from pathlib import Path
path = Path.cwd() / "ExampleList.md"
with path.open(mode="r", encoding="utf-8") as md_file:
content = md_file.read()
output = [line for line in content.splitlines() if line.startswith("*")
pythonHow to change file names
To change file names, only a few lines of code are required with Python pathlib
. The module uses the .with_name()
method for this, with which the name and file extension can be adapted. The corresponding code follows this pattern:
from pathlib import Path
md_path = Path("/Users/name/folder/blue.md")
txt_path = md_path.with_name("red.txt")
md_path.replace(txt_path)
pythonHow to copy files with Python pathlib
Even if Path itself does not have a method for copying, you can use .with_stem()
to duplicate a file. This creates a new file name without changing the file extension. This is an example of the appropriate code:
from pathlib import Path
source = Path("ExampleList.md")
destination = source.with_stem("new_example")
destination.write_bytes(source.read_bytes())
pythonHow to move files
When using Python pathlib
to move or delete files, it’s important to note that the system doesn’t prompt for confirmation. This means you should proceed carefully to avoid losing any important data. The .replace()
method is used to move a file, but if a file with the same name already exists at the destination, it will be overwritten. For this reason, it’s crucial to be confident in your decision. However, you can check in advance if this risk is present. The code would look like this:
from pathlib import Path
source = Path("blue.py")
destination = Path("red.py")
if not destination.exists():
source.replace(destination)
pythonHow to create empty files
To use Python pathlib
to create an empty file, enter this code:
from pathlib import Path
filename = Path("new.txt")
filename.exists()
filename.touch()
filename.exists()
filename.touch()
pythonReach your goal with GitHub: Deploy Now from IONOS offers you automated deployments that you can implement in just three steps. Based on the “push, build and deploy” principle, you can implement changes even faster. We will gladly advise you on the various plans we offer.