AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

Python Pathlib: All about this module

PARTAGEZ

The Python module pathlib offers a very effective method to interact with the paths of the file system in the programming language. In addition to being easy to handle, the conciseness of the code is a major advantage of this module.

What is pathlib in python?

In Python, the popular programming language, there are different methods to work with the paths of the file system. For example, from version 3.4, Python offers pathlibanother very useful and complete tool for Interact with the access roads, regardless of the operating system.

This module is particularly useful if you do not just want to read or modify the access paths, but also perform additional tasks and operations. It allows, among other things, to create and copy individual files and their components. This task is simplified by the upper interface of Python pathlib. This module is part of the standard library And replaces or combines many other methods.

Managed NextCloud of Ionos Cloud

Work as a team in your own cloud

  • Data security
  • Integrated collaboration tools
  • Accommodation in European data centers

Object -oriented representation of access paths

One of the great advantages of Python pathlib is that this module allows users to represent the paths no longer as character strings, but to have an object -oriented representation. While the previous method was often laborious and required several declarations, even for simple tasks, the syntax of the new module was considerably simplified. As you will generally work with the class Pathyou just have to import it before working on a project. This will allow you to create a more compact code afterwards. To import it, simply use the following command:

from pathlib import Path

python

To create an instance pathyou can already use Python pathlib. To do this, the following code is suitable, in which we use the two components « colors » and « blue.txt ». A simple command then allows you to create a new instance:

from pathlib import Path
bleu = Path("couleurs", "bleu.txt")
print(bleu)

python

The exit would then resemble this, as an example:

In the output, Python therefore places the separator of the operating system between the two components. In our example, it is a right oblique bar /but on a Windows machine, the output can contain a reverse oblique bar \ instead. For Linux and MacOS, the oblique bar is preserved.

Call directories with Python pathlib

After importing Pathyou can use the different class methods with Python pathlib. This includes, among other things, access to certain directories. For example, if you run the following code, you access your Current work directory ::

from pathlib import Path
Path.cwd()

python

This is important, among other things, if you want to open a file in the same repertoire as the one in which your current script is executed.

It is also possible to access the directory Home of the current user with pathlib of Python. It is recommended to choose this directory as a starting point, in order to be able to work with the corresponding access paths on different computers, if necessary. The corresponding code is as follows:

from pathlib import Path
Path.home()

python

Access using a character string

Instead of starting with your work directory or your personal directory, it is always possible to access a file or a directory Using a character string with python pathlib. Here is an example:

from pathlib import Path
Path(r"C:\Users\name\dossier\fichier.txt")

python

The chain is then converted to the access path, which facilitates its use. The little one r In front of the chain indicates that it is a « raw literal chain ». This makes it possible to ensure that the reverse oblique bar is used in this function. It can also be used to indicate a non -printable variable.

Connect paths or channels

Another method to create a new path with pathlib De Python is to connect paths or strings. For this, you have two possibilities.

Using a single oblique bar, you connect two elements to form a new path. For example :

from pathlib import Path
for chemin_fichier in Path.cwd().glob("*.txt"):
    nouveau_chemin = Path("exemple") / chemin_fichier.name
    chemin_fichier.rename(nouveau_chemin)

python

You can also use the method joinpath() To obtain the same result:

from pathlib import Path
Path.home().joinpath("exemple", "sous_dossier", "fichier.py")

python

Use individual components

If you want to decompose a path in its components and use them, Python pathlib also provides you with the appropriate tool. The following code gives some examples:

from pathlib import Path
path = Path(r"C:\Users\name\dossier\fichier.txt")
path
path.anchor
path.name
path.parent
path.parent.parent
path.stem
path.suffix

python

  • .anchor : Returns the root part of the path, like 'C:' under Windows or '/' under Unix.
  • .name : is limited to the name of the file, without reference to the directory.
  • .parent : identifies the directory in which the file is located; If the path is itself a repertoire, the parent repertoire is used.
  • .stem : focuses on the name of the file, without the extension.
  • .suffix : Returns the file extension (including the point).

The corresponding outputs are then as follows:

'C:\\'
'fichier.txt'
WindowsPath('C:/Users/name/dossier')
WindowsPath('C:/Users/name')
'fichier'
'.txt''

python

Read or write files

Although it is possible to write or read files by other means, Python pathlib Allows you to considerably reduce the code. To better illustrate its operation, we will create a simple list containing animals and plants. Here is what it looks like:

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact