search
HomeBackend DevelopmentPython TutorialHow to use the Python file system module pathlib library

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

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

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

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

import pathlib

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

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\路径拼接\真麻烦

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\路径拼接\真麻烦

通过 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

输出为什么会是 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

通过打印 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
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Explain the performance differences in element-wise operations between lists and arrays.Explain the performance differences in element-wise operations between lists and arrays.May 06, 2025 am 12:15 AM

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

How can you perform mathematical operations on entire NumPy arrays efficiently?How can you perform mathematical operations on entire NumPy arrays efficiently?May 06, 2025 am 12:15 AM

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

How do you insert elements into a Python array?How do you insert elements into a Python array?May 06, 2025 am 12:14 AM

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.

How can you make a Python script executable on both Unix and Windows?How can you make a Python script executable on both Unix and Windows?May 06, 2025 am 12:13 AM

TomakeaPythonscriptexecutableonbothUnixandWindows:1)Addashebangline(#!/usr/bin/envpython3)andusechmod xtomakeitexecutableonUnix.2)OnWindows,ensurePythonisinstalledandassociatedwith.pyfiles,oruseabatchfile(run.bat)torunthescript.

What should you check if you get a 'command not found' error when trying to run a script?What should you check if you get a 'command not found' error when trying to run a script?May 06, 2025 am 12:03 AM

When encountering a "commandnotfound" error, the following points should be checked: 1. Confirm that the script exists and the path is correct; 2. Check file permissions and use chmod to add execution permissions if necessary; 3. Make sure the script interpreter is installed and in PATH; 4. Verify that the shebang line at the beginning of the script is correct. Doing so can effectively solve the script operation problem and ensure the coding process is smooth.

Why are arrays generally more memory-efficient than lists for storing numerical data?Why are arrays generally more memory-efficient than lists for storing numerical data?May 05, 2025 am 12:15 AM

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

How can you convert a Python list to a Python array?How can you convert a Python list to a Python array?May 05, 2025 am 12:10 AM

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Can you store different data types in the same Python list? Give an example.Can you store different data types in the same Python list? Give an example.May 05, 2025 am 12:10 AM

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.

See all articles

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function