Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the Python standard library pathlib

Shulou Source: shulou.com Published: 2022-06-02 13:03:17 10月04日 Update

This article focuses on "how to use the Python standard library pathlib", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use the Python standard library pathlib.

Path problems are often dealt with when learning Python, especially in file operations and data processing. The most common and common is the os.path module, which treats paths as strings, which can lead to imperceptible errors if used improperly, and code that is difficult to reuse across platforms. Pathlib is a great Python standard library, which is super easy to use.

The pathlib module provides a high-level abstraction that works well on POSIX systems such as Linux and Windows. It abstracts the resource path and resource naming structure, isolates the file system interface from the os module, provides the operation as a method, and is easier to use.

The following picture perfectly illustrates the core of pathlib.

Pathlib basic components > from pathlib import Path > path = Path > > path.drive'C:' > path.root'/' > path.root'C:/' > > path.parentWindowsPath > > path.name'config.tar.gz' > path.stem'config.tar' > > path.suffix'.gz' > > path.suffixes [.tar', '.gz'] common attributes and basic methods

Common properties of pathlib

Path.parents # returns a list of all parent directories Path.parts # split path is similar to os.path.split (), but returns tuple Path.suffix # returns file suffix

Common basic methods of pathlib

Path.is_dir () # determines whether the directory Path.is_file () # is a file Path.exists () # determines whether the path exists Path.open () # opens the file (supports with) Path.resolve () # returns the absolute path Path.cwd () # returns the current directory Path.iterdir () # traverses a subdirectory of the directory or the file Path.mkdir () # Create directory Path.rename () # rename path Path.unlink () # delete file or directory (directory non-null triggered exception) Path.joinpath () # stitching path

Os and os.path VS pathlib

Pathlib replaces the common functions of os and os.path:

At this point, I believe you have a deeper understanding of "how to use the Python standard library pathlib". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Paths files directories commonly used standards methods modules processing learning content properties systems resources inappropriate practical deeper good advanced superior code Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology MariaDB Redmi Huawei OPPO Reno