L’auteur a choisi le COVID-19 Relief Fund pour recevoir un don dans le cadre du programme Write for DOnations.
Introduction
Python 3 inclut le module pathlib
, qui permet de manipuler les chemins des systèmes de fichiers de manière agnostique, quel que soit le système d’exploitation. pathlib
est similaire au module os.path
, mais pathlib
offre un niveau d’interface supérieur — et souvent plus pratique — qu’os.path
.
Nous pouvons identifier des fichiers sur un ordinateur avec des chemin hiérarchiques. Par exemple, nous pourrions identifier le fichier wave.txt
sur un ordinateur avec ce chemin: /Users/sammy/ocean/wave.txt
. Les systèmes d’exploitation représentent les chemins de manière légèrement différente. Windows peut représenter le chemin d’accès au fichier wave.txt
comme ceci, C:\Users\sammy\ocean\wave.txt
.
Vous pouvez trouver le module pathlib
utile si dans votre programme Python vous créez ou déplacez des fichiers dans le système de fichiers, listez des fichiers sur le système de fichiers qui correspondent tous à une extension ou un modèle donnés, ou créez des chemins de fichiers appropriés du système d’exploitation basés sur des collections de chaînes de caractères. Bien que vous puissiez utiliser d’autres outils (comme le module os.path
) pour accomplir plusieurs de ces tâches, le module pathlib
vous permet d’effectuer ces opérations avec un degré de lisibilité élevé et une quantité minimale de code.
Dans ce tutoriel, nous aborderons certaines des façons d’utiliser le module pathlib
pour représenter et manipuler les chemins du système de fichiers.
Conditions préalables
Pour tirer le meilleur parti de ce tutoriel, il est recommandé d’être familiarisé avec la programmation en Python 3. Vous pouvez consulter ces tutoriels pour obtenir les informations de base nécessaires:
- Comment coder en Python 3
Construire des instances Path
Le module pathlib
fournit plusieurs classes, mais l’une des plus importantes est la classe Path
. Les instances de la classe Path
représentent un chemin d’accès à un fichier ou un répertoire du système de fichiers de notre ordinateur.
Par exemple, le code suivant instancie une instance Path
qui représente une partie du chemin d’accès à un fichier wave.txt
:
from pathlib import Pathwave = Path("ocean", "wave.txt")print(wave)
Si nous exécutons ce code, nous obtiendrons le résultat suivant:
Output
ocean/wave.txt
from pathlib import Path
rend la classe Path
disponible pour notre programme. Ensuite, Path("ocean", "wave.txt")
instance une instance nouvelle Path
. L’impression de la sortie montre que Python a ajouté le séparateur approprié du système d’exploitation /
entre les deux composants de chemin que nous lui avons donné: "ocean"
et "wave.txt"
.
Remarque: En fonction de votre système d’exploitation, votre résultat peut varier légèrement par rapport aux exemples de sorties présentés dans ce tutoriel. Si vous utilisez Windows, par exemple, votre résultat pour ce premier exemple ressemblera peut-être à ocean\wave.txt
.
À présent, l’objet Path
assigné à la variable wave
contient un chemin relatif. En d’autres termes, ocean/wave.txt
pourrait exister à plusieurs emplacements de notre système de fichiers. À titre d’exemple, il peut exister dans /Users/user_1/ocean/wave.txt
ou /Users/user_2/research/ocean/wave.txt
, mais nous n’avons pas préciséà quel endroit exactement nous faisons référence. Un chemin absolu, en revanche, renvoie sans ambiguïté à un seul emplacement du système de fichiers.
Vous pouvez utiliser Path.home()
pour obtenir le chemin absolu du répertoire d’accueil de l’utilisateur actuel:
home = Path.home()wave_absolute = Path(home, "ocean", "wave.txt")print(home)print(wave_absolute)
Si nous exécutons ce code, nous obtiendrons en gros le résultat suivant:
Output
/Users/sammy/Users/sammy/ocean/wave.txt
Remarque: Comme mentionné précédemment, votre sortie varie en fonction de votre #système d’exploitation. Votre répertoire d’accueil, bien sûr, sera également différent de /Users/sammy
.
Path.home()
renvoie une instance Path
avec un chemin absolu vers le répertoire d’accueil de l’utilisateur actuel. Nous passons ensuite dans cette instance Path
et les chaînes "ocean"
et "wave.txt"
dans un autre constructeur Path
pour créer un chemin absolu vers le fichier wave.txt
. La sortie montre que la première ligne est le répertoire d’accueil, et la deuxième ligne est le répertoire d’accueil plus ocean/wave.txt
.
Cet exemple illustre également une caractéristique importante de la classe Path
: le constructeur Path
accepte les chaînes et les objets Path
préexistants.
Examinons de plus près le support des chaînes et des objets Path
dans le constructeur Path
:
shark = Path(Path.home(), "ocean", "animals", Path("fish", "shark.txt"))print(shark)
Si nous exécutons ce code Python, nous obtiendrons un résultat similaire au suivant:
Output
/Users/sammy/ocean/animals/fish/shark.txt
shark
est un Path
vers un fichier que nous avons construit en utilisant les objets Path
(Path.home()
et Path("fish", "shark.txt")
) et les chaînes ("ocean"
et "animals"
). Le constructeur Path
traite intelligemment les deux types d’objets et les joint de manière propre en utilisant le séparateur du système d’exploitation approprié, dans ce cas /
.
Accéder aux attributs de fichier
Maintenant que nous avons appris comment construire des instances Path
, examinons comment vous pouvez utiliser ces instances pour accéder aux informations sur un fichier.
Nous pouvons utiliser les attributs name
et suffix
pour accéder aux noms de fichier et aux suffixes:
wave = Path("ocean", "wave.txt")print(wave)print(wave.name)print(wave.suffix)
En exécutant ce code, nous obtiendrons un résultat similaire à ce qui suit:
Output
/Users/sammy/ocean/wave.txtwave.txt.txt
Cette sortie montre que le nom du fichier à la fin de notre chemin est wave.txt
et le suffixe de ce fichier est .txt
.
Les instances Path
offrent également la fonction with_name
, qui permet de créer de manière transparente un nouvel objet Path
portant un nom différent:
wave = Path("ocean", "wave.txt")tides = wave.with_name("tides.txt")print(wave)print(tides)
Si nous exécutons ce code, nous obtiendrons le résultat suivant:
ocean/wave.txtocean/tides.txt
Le code construit d’abord une instance Path
qui pointe vers un fichier nommé wave.txt
. Ensuite, nous appelons la méthode with_name
sur wave
pour renvoyer une seconde instance Path
qui pointe vers un nouveau fichier nommé tides.txt
. La partie du chemin correspondant au répertoire ocean/
reste inchangée, ce qui fait que le chemin final devient ocean/tides.txt
Accéder aux ascendants
Il est parfois utile d’accéder à des répertoires qui contiennent un chemin d’accès donné. Prenons un exemple:
shark = Path("ocean", "animals", "fish", "shark.txt")print(shark)print(shark.parent)
Si nous exécutons ce code, nous obtiendrons un résultat qui ressemble au suivant:
Output
ocean/animals/fish/shark.txtocean/animals/fish
L’attribut parent
d’une instance Path
renvoie l’ascendant le plus immédiat d’un chemin de fichier donné. Dans ce cas, il renvoie le répertoire qui contient le fichier shark.txt
: ocean/animals/fish
.
Nous pouvons accéder à l’attribut parent
plusieurs fois de suite pour remonter l’arbre d’ascendance d’un fichier donné:
shark = Path("ocean", "animals", "fish", "shark.txt")print(shark)print(shark.parent.parent)
Si nous exécutons ce code, nous obtiendrons le résultat suivant :
Output
ocean/animals/fish/shark.txtocean/animals
La sortie est similaire à la sortie précédente, mais maintenant nous avons traversé un autre niveau plus élevé en accédant à .parent
une seconde fois. Deux répertoires plus haut que shark.txt
nous avons le répertoire ocean/animals
.
Utiliser Glob pour lister les fichiers
Il est également possible d’utiliser la classe Path
pour lister les fichiers à l’aide de la méthode glob
.
Supposons que nous avons une structure de répertoire qui ressemblait à ceci:
└── ocean ├── animals │ └── fish │ └── shark.txt ├── tides.txt └── wave.txt
Le répertoire ocean
contient les fichiers tides.txt
et wave.txt
. Nous avons un fichier nommé shark.txt
imbriqué sous le répertoire ocean
, un répertoire animals
et un répertoire fish
: ocean/animals/fish
.
Pour lister tous les fichiers .txt
du répertoire ocean
, nous pourrions dire:
for txt_path in Path("ocean").glob("*.txt"): print(txt_path)
Ce code donnerait un résultat du type:
Output
ocean/wave.txtocean/tides.txt
Le modèle glob "*.txt"
trouve tous les fichiers se terminant par .txt.
Comme l’exemple de code exécute ce glob dans le répertoire ocean
, il renvoie les deux fichiers .txt
du répertoire ocean
: wave.txt
et tides.txt
.
Remarque: Si vous souhaitez dupliquer les sorties indiquées dans cet exemple, vous devrez imiter la structure de répertoire illustrée ici sur votre ordinateur.
Nous pouvons également utiliser la méthode glob
de manière récursive. Pour lister tous les fichiers .txt
du répertoire ocean
et tous ses sous-répertoires, nous pourrions dire:
for txt_path in Path("ocean").glob("**/*.txt"): print(txt_path)
Si nous exécutons ce code, nous obtiendrions le résultat suivant:
Output
ocean/wave.txtocean/tides.txtocean/animals/fish/shark.txt
La partie **
du modèle glob correspondra à ce répertoire et tous les répertoires en dessous, de manière récursive. Donc, non seulement nous avons les fichiers wave.txt
et tides.txt
dans la sortie, mais nous recevons également le fichier shark.txt
qui a été imbriqué sous ocean/animals/fish
.
Calculer les chemin relatifs
Nous pouvons utiliser la méthode Path.relative_to
pour calculer les chemins par rapport aux autres. La méthode relative_to
est utile lorsque, par exemple, vous souhaitez récupérer une partie d’un long chemin de fichier.
Prenons le cas du code suivant:
shark = Path("ocean", "animals", "fish", "shark.txt")below_ocean = shark.relative_to(Path("ocean"))below_animals = shark.relative_to(Path("ocean", "animals"))print(shark)print(below_ocean)print(below_animals)
Si nous exécutons ce code, nous obtiendrons le résultat suivant:
Output
ocean/animals/fish/shark.txtanimals/fish/shark.txtfish/shark.txt
La méthode relative_to
renvoie un nouvel objet Path
relatif à l’argument donné. Dans notre exemple, nous calculons le Path
d’accès à shark.txt
par rapport au répertoire ocean
, puis par rapport aux répertoires ocean
et animals
.
Si la fonction relative_to
ne peut pas calculer de réponse parce que nous lui fournissons un chemin non relié, elle génère une ValueError
:
shark = Path("ocean", "animals", "fish", "shark.txt")shark.relative_to(Path("unrelated", "path"))
Nous obtiendrons une exception ValueError
qui a été soulevée à partir de ce code et qui ressemblera à quelque chose comme ceci:
Output
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/Python3.8/pathlib.py", line 899, in relative_to raise ValueError("{!r} does not start with {!r}"ValueError: 'ocean/animals/fish/shark.txt' does not start with 'unrelated/path'
unrelated/path
n’est pas une partie de ocean/animals/fish/shark.txt
, Python n’a donc aucun moyen pour de calculer un chemin relatif pour nous.
Conclusion
Le module pathlib
est une partie puissante de la bibliothèque standard Python qui nous permet de manipuler rapidement les chemins du système de fichiers sur n’importe quel système d’exploitation. Dans ce tutoriel, nous avons appris à utiliser certains des utilitaires clés de pathlib
pour accéder aux attributs de fichier, lister les fichiers avec des modèles glob, et parcourir les fichiers et les répertoires parents.
Le module pathlib
propose des classes et des utilitaires supplémentaires que nous n’avons pas abordés dans ce tutoriel. Maintenant que vous disposez d’une base de référence, vous pouvez utiliser la documentation du module pathlib
pour en savoir plus sur d’autres classes et utilitaires disponibles.
Si vous souhaitez utiliser d’autres bibliothèques Python, consultez les tutoriels suivants:
- Comment utiliser le module des collections en Python 3
- Comment utiliser le module sqlite3 en Python 3
- Comment utiliser ThreadpoolExecutor en Python 3
FAQs
What does Pathlib path () do? ›
Path() is the child node of PurePath() , it provides handling operations with the ability to do writing operations on your path. When you instantiate Path() , it creates two classes to handle Windows paths and non-Windows paths.
What is Pathlib module? ›The pathlib module initially appeared in Python 3.4, and it has since been improved in each succeeding version. Pathlib is an object-oriented filesystem interface that provides a more natural, platform-agnostic, and pythonic way to interact with the filesystem.
What does __ file __ mean in Python? ›__file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module.
What is the path of Python 3? ›Note − /usr/local/bin/python3 is the path of the Python directory.
What is the purpose of the Path option? ›PATH is an environmental variable in Linux and other Unix-like operating systems that tells the shell which directories to search for executable files (i.e., ready-to-run programs) in response to commands issued by a user.
What is the purpose of pathname? ›The pathname is a specific label for a file's directory location while within an operating system. In traditional DOS command line systems, the user would type the entire file pathname into the system to be directed to that file where it is located inside of the operating system.
How do I use Path module in Python? ›- path. basename. This function gives us the last part of the path which may be a folder or a file name. ...
- path. dirname. This function gives us the directory name where the folder or file is located. ...
- path. isfile. ...
- path. normpath.
- Creating a path object. ...
- Creating a path by passing folder and file name. ...
- Converting a relative path to an absolute path. ...
- Reading the text using the path. ...
- Relative path to another path. ...
- Comparing two paths. ...
- File or directory.
The OS library will return a string, whereas the Pathlib will return an object of PosixPath. The benefit of having PosixPath returned is that we can directly use the returned object to do a lot more further operations.
What does __ name __ == '__ main __' mean? ›In Short: It Allows You to Execute Code When the File Runs as a Script, but Not When It's Imported as a Module. For most practical purposes, you can think of the conditional block that you open with if __name__ == "__main__" as a way to store code that should only run when your file is executed as a script.
What does __ name __ == '__ main __' mean in Python? ›
A Python programme uses the condition if __name__ == '__main__' to only run the code inside the if statement when the program is run directly by the Python interpreter. The code inside the if statement is not executed when the file's code is imported as a module.
What are main functions in Python? ›The main function in Python acts as the point of execution for any program. Defining the main function in Python programming is a necessity to start the execution of the program as it gets executed only when the program is run directly and not executed when imported as a module.
What does add Python 3.10 to path mean? ›What exactly does adding Python to PATH do? Adding Python to PATH makes it possible for you to run (use) Python from your command prompt (also known as command-line or cmd). This lets you access the Python shell from your command prompt.
What is __ path __ in Python? ›Packages support one more special attribute, __path__ . This is initialized to be a list containing the name of the directory holding the package's __init__.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.
What are the three libraries in Python? ›- TensorFlow.
- Scikit-Learn.
- Numpy.
- Keras.
- PyTorch.
- LightGBM.
- Eli5.
- SciPy.
Disable the path limit length is recommended after Python setup is successful, because if python was installed in a directory with a path length greater than 260 characters, adding it to the path could fail. So don't worry about that action and proceed to it.
Why path is needed for Python? ›If you type python into the command line, the command line will look in each folder in the PATH environment variable for a python executable. Once it finds one, it'll stop searching. This is why you prepend the path to your Python executable to PATH .
What is my system path? ›The PATH is the system variable that your operating system uses to locate needed executables from the command line or Terminal window. The PATH system variable can be set using System Utility in control panel on Windows, or in your shell's startup file on Linux and Solaris.
What is an example of file path? ›For example, /home/sally/statusReport is an absolute path. All of the information needed to locate the file is contained in the path string. A relative path needs to be combined with another path in order to access a file. For example, joe/foo is a relative path.
How do I read a file path? ›Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document. Properties: Click this option to immediately view the full file path (location).
What does ~/ mean in path? ›
The dot-dot ( .. ) represents one level above the current directory. The forward slash ( / ) represents the "root" of the filesystem. (Every directory/file in the Linux filesystem is nested under the root / directory.) The tilde ( ~ ) represents the home directory of the currently logged in user.
How do you write a path in Python? ›On Windows, paths are written using backslashes ( \ ) as the separator between folder names. On Unix based operating system such as macOS, Linux, and BSDs, the forward slash ( / ) is used as the path separator.
How do I set path for Python? ›- Right-clicking This PC and going to Properties.
- Clicking on the Advanced system settings in the menu on the left.
- Clicking on the Environment Variables button on the bottom right.
- In the System variables section, selecting the Path variable and clicking on Edit.
- Right click on My Computer and click on properties.
- Click on Advanced System settings.
- Click on Environment Variable tab.
- Click on new tab of user variables.
- Write path in variable name.
- Copy the path of Python folder.
- Paste path of Python in variable value.
Get the path of current file (script) in Python: __file__ In Python, you can get the path (location) of the current file, i.e., currently running script file ( . py ) with __file__ . __file__ is useful for reading other files based on the location of the current file.
How do I find my Python path? ›- Type 'Python' in the Windows Search Bar.
- Right-click on the Python App, and then select “Open file location“
- Right-click on the Python shortcut, and then select Properties.
- Click on “Open File Location“
The os. path. exists() method in Python is used to check whether the specified path exists or not. This method can be also used to check whether the given path refers to an open file descriptor or not.
What are the advantages of using Pathlib? ›The Python pathlib module provides an easier method to interact with the filesystem no matter what the operating system is. It allows a more intuitive, more pythonic way to interface with file paths (the name of a file including any of its directories and subdirectories). In the os module, paths are regular strings.
What are two advantages of using Pathlib Path objects for navigating file systems over using string objects? ›With pathlib , file paths can be represented by proper Path objects instead of plain strings as before. These objects make code dealing with file paths: Easier to read, especially because / is used to join paths together. More powerful, with most necessary methods and properties available directly on the object.
What is the difference between os and os Path? ›Strictly speaking, os. path is an alias for an OS-specific module with its own name. import os. path is redundant if you already have import os , since os also has an attribute path that refers to the same module.
What is __ in Python called? ›
Underscore (_) in Python
Single Underscore: Single Underscore in Interpreter. Single Underscore after a name. Single Underscore before a name. Single underscore in numeric literals.
Python __add__() function is one of the magic methods in Python that returns a new object(third) i.e. the addition of the other two objects. It implements the addition operator “+” in Python.
What is the difference between _ and __ in Python? ›Double Leading and Trailing Underscore( __var__ ): Indicates special methods defined by the Python language. Avoid this naming scheme for your own attributes. Single Underscore( _ ): Sometimes used as a name for temporary or insignificant variables (“don't care”).
What is '__ main __'? ›__main__ — Top-level code environment. In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.
What are __ __ methods in Python? ›These methods provides special syntactic features or do special things. For example, __file__ indicates the location of Python file, __eq__ is executed when a == b expression is executed.
How to create a module in Python? ›- Save this code in a file named mymodule.py. ...
- Import the module named mymodule, and call the greeting function: ...
- Save this code in the file mymodule.py. ...
- Import the module named mymodule, and access the person1 dictionary:
- Python Built-in Functions.
- Python Recursion Functions.
- Python Lambda Functions.
- Python User-defined Functions.
- One – one function (Injective function)
- Many – one function.
- Onto – function (Surjective Function)
- Into – function.
- Polynomial function.
- Linear Function.
- Identical Function.
- Quadratic Function.
- Functions with arguments and return values. This function has arguments and returns a value: ...
- Functions with arguments and without return values. ...
- Functions without arguments and with return values. ...
- Functions without arguments and without return values.
In short, “pythonic” describes a coding style that leverages Python's unique features to write code that is readable and beautiful. To help us better understand, let's briefly look at some aspects of the Python language.
How to check version of Python in cmd? ›
i) Windows:
In Windows operating systems, we can use the command python --version to check the python version.
...
You can find the Python application path by following these steps:
- Type “Python” in the Windows Search Bar.
- Right-click on the Python App, and then select “Open file location“
- Right-click again on the Python shortcut, and then select “Open file location“
sys. path and PATH are two entirely different variables. The PATH environment variable specifies to your shell (or more precisely, the operating system's exec() family of system calls) where to look for binaries, whereas sys. path is a Python-internal variable which specifies where Python looks for installable modules.
What is the purpose of __ Str__ method? ›Python __str__()
This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.
The Python standard library contains well over 200 modules, although the exact number varies between distributions.
What Python skills are required for data analyst? ›- Programming with Python to perform complex statistical analysis of large datasets.
- Performing SQL queries and web-scraping to explore and extract data from databases and websites.
- Performing efficient data analysis from start to finish.
- Building insightful data visualizations to tell stories.
- TensorFlow.
- NumPy.
- SciPy.
- Pandas.
- Matplotlib.
- Keras.
- SciKit-Learn.
- PyTorch.
The pandas library has become the backbone of data analysis in Python; it's a must-know for those of you wanting to learn how to work with data. With pandas, you can read in data from a file, do some exploratory data analysis and visualizations, manipulate the data, calculate statistics, and much more.
What is the difference between path and PurePath in Pathlib Python? ›PurePath is the set of functions that can figure out things just from the paths you give it. it doesn't need to look up anything. Path is the set of functions that need to do actual look ups on the filesystem. Path can inherit the PurePath functions because they will still work even that way.
How does path work in Django? ›The path function is contained with the django. urls module within the Django project code base. path is used for routing URLs to the appropriate view functions within a Django application using the URL dispatcher.
Why you should start using Pathlib as an alternative to the os module? ›
👉 It allows you to iterate on directories and perform pattern matching. Let's assume you have a Path object that points to a directory. Pathlib allows you to easily iterate over that directory's content and also get files and folders that match a specific pattern.
Should I disable path limit for Python? ›Disable the path limit length is recommended after Python setup is successful, because if python was installed in a directory with a path length greater than 260 characters, adding it to the path could fail.
Why is Pathlib better than OS? ›The Python pathlib module provides an easier method to interact with the filesystem no matter what the operating system is. It allows a more intuitive, more pythonic way to interface with file paths (the name of a file including any of its directories and subdirectories). In the os module, paths are regular strings.
What are the two types of paths in Linux? ›There are two kinds of path called absolute and relative. An absolute path starts from the root of the file system, the highest level of the structure where the files are stored, which remember is represented by the slash character.
How do I join two paths in Python? ›path. join() method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator ('/') following each non-empty part except the last path component.
What is a path in coding? ›A path is a string of characters used to uniquely identify a location in a directory structure. It is composed by following the directory tree hierarchy in which components, separated by a delimiting character, represent each directory.
What can I use instead of OS Path? ›An alternative approach to os is to use the pathlib library instead. pathlib is a more object-oriented way of checking files, which offers many options for file interaction. In this example, we've created the object log_file using the Path() class.
Why do we use OS Path in Python? ›The os. path module is a very extensively used module that is handy when processing files from different places in the system. It is used for different purposes such as for merging, normalizing and retrieving path names in python .
Is it OK to uninstall Python? ›If someone installed it deliberately, you can remove it without hurting anything. On Windows, use the Add/Remove Programs icon in the Control Panel. If Python was installed by a third-party application, you can also remove it, but that application will no longer work.
How do I turn off path limit? ›...
Choose the DWORD (32-bit) Value.
- Right-click the newly added key and choose Rename.
- Name the key LongPathsEnabled.
- Press Enter.
How do I get rid of path too long error? ›
If you see this error there are several solutions: 1) Instead of right clicking on the file to extract it, left click on the file to enter the zip directly. Then look for long folder names and make them shorter. Then close the zip file and extract it again.