Table of Contents
1. Official definition of pathlib library
2. Pathlib cheats
1. Basic usage
Path.
1. Get the current file path
method
In the os module, if we want to get the parent directory of a certain file, the os module is written as:
When you use pathlib, let’s experience its convenience together!
4、 其他封装
四、pathlib.PurePath的使用
1、 PurePath.match
2、 PurePath的子类:PurePosixPath(非Windows系统)、PureWindowsPath
Home Backend Development Python Tutorial How to use the Python file system module pathlib library

How to use the Python file system module pathlib library

May 13, 2023 pm 11:49 PM
python pathlib

1. Official definition of pathlib library

pathlib is a built-in library of Python. The definition given by the Python documentation is Object-oriented filesystem paths. pathlib provides classes representing file system paths, with semantics applicable to different operating systems.

The path classes are divided between pure paths, which provide pure computational operations without I/O, and concrete paths, which inherit pure paths but also provide I/O operations.

2. Pathlib cheats

1. Basic usage

  • Path.iterdir() # Traverse the subdirectories of the directory or File

  • Path.is_dir() # Determine whether it is a directory

  • ##Path.

    glob () # Filter directory (return to generator)

  • ##Path.
  • resolve

    () # Return absolute path

  • Path .
  • exists

    () # Determine whether the path exists

  • Path.
  • open

    () # Open the file (supports with)

  • Path.
  • unlink

    () # Delete a file or directory (the directory is not empty and triggers an exception)

  • 2. Basic attributes

    Path.
  • parts

    # Splitting the path is similar to os.path.split(), but returns a tuple

  • Path.
  • drive

    # Returns the drive name

  • Path.
  • root

    # Returns the root directory of the path

  • Path.
  • anchor

    # Automatically determine and return drive or root

  • Path.
  • parents

    # Return a list of all parent directories

  • 3. Change path

    Path.
  • with_name

    () # Change the path name, change the last level path name

  • Path.
  • with_suffix

    () # Change path suffix

  • 4, Splice path

    Path.
  • joinpath

    () #Join path

  • Path.
  • relative_to

    () #Calculate relative path

    ##5 , Test path

Path.
    match
  • () # Test whether the path matches pattern

    Path.
  • is_dir
  • () # Whether it is a file

    ##Path.

    is_absolute
  • () # Whether it is an absolute path
  • Path .

    is_reserved
  • () # Whether it is a reserved path
  • Path.

    exists
  • () # Determine whether the path actually exists
  • 6. Other methods

Path.

cwd
    () # Return the path object of the current directory
  • Path.

    home
  • () # Return the current user’s home path object
  • Path.

    stat
  • () # Return path information, Same as os.stat()
  • Path.

    chmod
  • () # Change path permissions, similar to os.chmod()
  • Path.

    expanduser
  • () # Expand~Return full path object
  • Path.

    mkdir
  • () # Create directory
  • Path.

    rename
  • () # Rename the path
  • Path.

    rglob
  • () # Recursively traverse all Files in subdirectories
  • 3. The difference between os and pathlib.Path

  • Compared with the path method of the os module, the Path of the Python3 standard library pathlib module operates on the path. It will be simpler.

1. Get the current file path

When using the os module, you can directly get the current file path through the

getcwd()

method

In Pycharm, You can use os.path.dirname(__file__) to get the current file path, because Python does not provide the concept of __file__, which is provided by Pycharm:

import os

print(os.getcwd())  # C:\Users\bobin.yang\PycharmProjects\untitled
print(os.path.dirname(__file__))  # C:/Users/bobin.yang/PycharmProjects/untitled
Copy after login

In the pathlib module, pass Path.cwd() method can directly obtain the current file path, we can give it a try:

import pathlib

print(pathlib.Path.cwd())  # C:\Users\bobin.yang\PycharmProjects\untitled
Copy after login

Through Pycharm we can use shortcut keys ctrl left mouse button Click to view a detailed introduction to this method.

As can be seen from the above picture, the cwd() method is just an encapsulation of the

getcwd()

method in the os library. It looks even worse. But the official launch is definitely not a fiction. Now let us reveal the secret together. 2. Get the upper/upper directory The above case seems to make the use of the pashlib library more complicated. In order to reveal the secret, we can only feel the composition of the pathlib library and understand pathlib How libraries bring us convenience.

In the os module, if we want to get the parent directory of a certain file, the os module is written as:

import os

print(os.path.dirname(os.path.dirname(os.getcwd())))  # C:\PycharmProjects
Copy after login

In the pathlib library, it can be achieved in this simple way:

import pathlib

print(pathlib.Path.cwd().parent)   # C:\PycharmProjects
Copy after login

And if you need to find his grandfather, just ask for another

.parent

. Compared with the os module's

os.path.dirname()

, is it too convenient? 3. Path splicingIf you want to splice the path in its parent directory, you may need to write such a long string of code through the os module:

import os

print(os.path.join(os.path.dirname(os.getcwd()), '路径拼接', '真麻烦'))  # C:\PycharmProjects\路径拼接\真麻烦
Copy after login

When you use pathlib, let’s experience its convenience together!

# /Users/mac/test.py
import os

paths = ('路径拼接', '真麻烦')
print(pathlib.Path.cwd().parent.joinpath(*paths))  # C:\PycharmProjects\路径拼接\真麻烦
Copy after login

通过 pathlib 库拼接路径,你可以很方便的调节他在他祖辈的位置,妙哉。

4、 其他封装

pathlib 封装了很多的 os.path 中的方法,如下所示:

  • os.path.expanduser() --> pathlib.Path.home()

  • os.path.expanduser() --> pathlib.Path.expanduser()

  • os.stat() --> pathlib.Path.stat()

  • os.chmod() --> pathlib.Path.chmod()

四、pathlib.PurePath的使用

上一节的操作大部分都是通过 pathlib 库中的 Path 实现,其实他还有一个更加高大上的模块,也就是我们这一节的主角:pathlib.PurePath

PurePath 是一个纯路径对象,纯路径对象提供了实际上不访问文件系统的路径处理操作。

有三种方法可以访问这些类,我们也称之为 flavor 。

1、 PurePath.match

下面让我们来实现一个神奇的功能,判断当前的路径下是否有符合'*.py'规则的文件。

import pathlib

print(pathlib.PurePath(__file__).match('*.py'))  # True
Copy after login

输出为什么会是 True 呢?因为当前文件夹下不就有一个 test.py 吗?

2、 PurePath的子类:PurePosixPath(非Windows系统)、PureWindowsPath

看见 pathlib.PurePath 后面跟着 match,那是不是能说明他是个对象,而不是一个单纯的路径字符串,因此我们可以试着打印 pathlib.PurePath 看一看。

import pathlib

os_path = os.path.dirname(__file__)
print(os_path)  # C:/PycharmProjects/untitled

pure_path = pathlib.PurePath(__file__)
print(pure_path)  # C:\PycharmProjects\untitled\run.py
print(type(pure_path))  # <class &#39;pathlib.PureWindowsPath&#39;>


print(pathlib.PurePath(__file__).match(&#39;*.py&#39;))  # True
Copy after login

通过打印 os.path 获取当前路径的结果,得到一个路径字符串;而通过 pathlib.PurePath 则获得了一个 PurePosixPath 对象,并且由此得到的路径包括了当前文件 run.py。

The above is the detailed content of How to use the Python file system module pathlib library. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles