Table of Contents
1. 为什么需要pathlib
2. pathlib的使用
2.1 创建路径
2.2 读写文件
2.3 路径的属性
2.4 移动和删除文件
3. 操作系统的差异
附:pathlib和os的区别
Home Backend Development Python Tutorial How to handle file paths using Python's pathlib module?

How to handle file paths using Python's pathlib module?

Apr 21, 2023 pm 01:34 PM
python pathlib

    1. 为什么需要pathlib

    在pathlib出现之前, Python 的标准库os.path 支持操作文件路径, 使用字符串表示文件路径。

    In [1]: import os.path
     
    In [2]: os.path.abspath('test')
    Out[2]: 'C:\\Users\\Public\\Documents\\test'
    Copy after login

    如以上代码, abspath函数的返回是一个字符串. 如果想要获取父目录, 需要使用字符串的split方法

    In [3]: path = os.path.abspath('test')
     
    In [4]: path.rsplit('\\', maxsplit=1)[0]
    Out[4]: 'C:\\Users\\Public\\Documents'
     
    Out[5]: os.path.join(path, 'data.txt')
    Out[5]: 'C:\\Users\\Public\\Documents\\test\\data.txt'
    Copy after login

    但是路径并不只是一个字符串, 如果需要对文件进行操作, 需要结合使用多个标准库的功能, 如: 需要移动当前目录下的一些文件到备份目录, 需要使用 os, glob, 和 shutil 库.

    import glob
    import os
    import shutil
     
    for file_name in glob.glob('*.txt'):
        new_path = os.path.join('backup', file_name)
        print(new_path)
        shutil.move(file_name, new_path)
    Copy after login

    有了pathlib, 使得上述的问题变得更加轻松, pathlib 创建的Path对象, 可以直接通过正斜杠运算符 '/' 连接字符串生成新的对象.

    In [1]: import pathlib
     
    In [2]: path = pathlib.Path()
    In [3]: path
    Out[3]: WindowsPath('.')
     
    In [4]: path.absolute() / 'test' / 'data.txt'
    Out[4]: WindowsPath('C:/Users/Public/Documents/test/data.txt')
    Copy after login

    另外pathlib还提供了很多方便的功能, 下面来介绍一下pathlib的常用方法

    2. pathlib的使用

    2.1 创建路径

    前面用到了 pathlib.Path() 获取当前路径的方法, 也可以显示的传入路径字符串进行路径创建.支持相对路径和绝对路径字符串的传递

    In [5]: pathlib.Path('test')
    Out[5]: WindowsPath('test')
     
    In [6]: pathlib.Path('C:/Users/Public/Documents/test')
    Out[6]: WindowsPath('C:/Users/Public/Documents/test')
    Copy after login

    另外 Path类还提供了一些类方法来更方便的获取路径. 如 .cwd()(当前工作目录)和.home()(您用户的主目录)

    In [7]: pathlib.Path.cwd()
    Out[7]: WindowsPath('C:/Users/Public/Documents')
     
    In [8]: pathlib.Path.home()
    Out[8]: WindowsPath('C:/Users/wyy')
    Copy after login

    2.2 读写文件

    通常, Python中读写文件时使用内置的 open 函数, open函数支持 path对象为参数打开文件.

    In [7]: data_file = pathlib.Path.cwd() / 'data.txt'
     
    In [8]: with open(data_file, 'w') as f:
        ...:     f.write('testdata')
    Copy after login

    path对象 提供了 open() 方法, 可以作为等效替代

    In [9]: with data_file.open(mode='r') as f:
       ...:     print(f.read())
    testdata
    Copy after login

    对于简单的文件读写, pathlib 库中还提供了几个方便的方法

    • .read_text():以文本模式打开path对象, 并返回字符串数据。

    • .read_bytes():以二进制模式打开path对象, 并返回字节数据。

    • .write_text(): 以文本模式打开path对象, 并写入字符串数据。

    • .write_bytes():以二进制模式打开path对象, 并写入字节数据。

    In [10]: data_file.read_text()
    Out[10]: 'testdata'
     
    In [11]: data_file.write_text('aloha')
    Out[11]: 5
     
    In [12]: data_file.read_text()
    Out[12]: 'aloha'
    Copy after login

    2.3 路径的属性

    路径的不同部分可以方便地作为属性使用.

    • .name 文件名

    • .parent 当前文件或目录的父目录

    • .stem 不带后缀的文件名

    • .suffix 文件扩展名

    • .anchor 目录的锚点, (路径前的目录部分)

    In [13]: data_file
    Out[13]: WindowsPath('C:/Users/Public/Documents/data.txt')
     
    In [14]: data_file.name
    Out[14]: 'data.txt'
     
    In [15]: data_file.stem
    Out[15]: 'data'
     
    In [16]: data_file.suffix
    Out[16]: '.txt'
     
    In [17]: data_file.anchor
    Out[17]: 'C:\\'
     
    In [18]: data_file.parent
    Out[18]: WindowsPath('C:/Users/Public/Documents')
    Copy after login

    2.4 移动和删除文件

    要移动文件, 可以使用 .replace() 方法, 需要注意的是, 如果目的地址的文件已经存在, .replace() 将会覆盖它. 使用pathlib 实现要移动当前目录下的txt文件到备份目录代码如下.

    In [19]: cwd = pathlib.Path.cwd()
     
    In [20]: for p in cwd.glob('*.txt'):
        ...:     p.replace(p.parent/'backup'/p.name)
    Copy after login

    如果需要重命名文件或者拓展名, 可以使用 .with_name() 和 .with_suffix()

    In [21]: data_file
    Out[21]: WindowsPath('C:/Users/Public/Documents/data.txt')
     
    In [22]: data_file.with_name(data_file.stem+'01').with_suffix('.txt.bak')
    Out[22]: WindowsPath('C:/Users/Public/Documents/data01.txt.bak')
    Copy after login

    3. 操作系统的差异

    windows系统使用的文件路径分割符是 '/' linux和mac系统使用的文件路径分割符是 '\' .

    当我们示例化一个pathlib.Path对象时, 根据操作系统的不同, 返回的时是 一个 WindowsPath, 或一个 PosixPath 对象. 这个特性使得编写跨平台兼容的代码变得相当容易. 当然也可以显式的使用 pathlib.WindowsPath.cwd() 来创建 WindowsPath 对象.

    此外, pathlib还提供了提供纯计算操作而没有 I/O 的 纯路径对象. 各个路径的关系如下:

    How to handle file paths using Pythons pathlib module?

    在一些用例中纯路径很有用,例如:

    1. 如果你想要在 Unix 设备上操作 Windows 路径(或者相反)。你不应在 Unix 上实例化一个 WindowsPath,但是你可以实例化 PureWindowsPath。

    2. 你只想操作路径但不想实际访问操作系统。在这种情况下,实例化一个纯路径是有用的,因为它们没有任何访问操作系统的操作。

    附:pathlib和os的区别

    pathlib在不同操作系统之间切换非常简单

    os操作导入模块不统一。 有时候需要导入 os,有时候又需要导入 os.path,而pathlib统一from pathlib import *即可。

    os返回的类型通常是字符串,但是路径和字符串并不等价,所以用os的时候,操作路径时有时候需要引入其他类库来协助操作;Pathlib模块则是面向对象,处理起来更方便

    比如在windows中:二者找到当前目录的操作是这样的

    import os
    from pathlib import *
    Path.cwd(),os.getcwd()
    #(WindowsPath('C:/Users/16000'), 'C:\\Users\\16000')
    Copy after login

    在linux中,是这样的

    How to handle file paths using Pythons pathlib module?

    The above is the detailed content of How to handle file paths using Python's pathlib module?. 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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    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)

    Is the conversion speed fast when converting XML to PDF on mobile phone? Is the conversion speed fast when converting XML to PDF on mobile phone? Apr 02, 2025 pm 10:09 PM

    The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

    How to convert XML files to PDF on your phone? How to convert XML files to PDF on your phone? Apr 02, 2025 pm 10:12 PM

    It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

    What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

    There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

    Is there a mobile app that can convert XML into PDF? Is there a mobile app that can convert XML into PDF? Apr 02, 2025 pm 09:45 PM

    There is no APP that can convert all XML files into PDFs because the XML structure is flexible and diverse. The core of XML to PDF is to convert the data structure into a page layout, which requires parsing XML and generating PDF. Common methods include parsing XML using Python libraries such as ElementTree and generating PDFs using ReportLab library. For complex XML, it may be necessary to use XSLT transformation structures. When optimizing performance, consider using multithreaded or multiprocesses and select the appropriate library.

    Recommended XML formatting tool Recommended XML formatting tool Apr 02, 2025 pm 09:03 PM

    XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

    How to convert XML to PDF on your phone? How to convert XML to PDF on your phone? Apr 02, 2025 pm 10:18 PM

    It is not easy to convert XML to PDF directly on your phone, but it can be achieved with the help of cloud services. It is recommended to use a lightweight mobile app to upload XML files and receive generated PDFs, and convert them with cloud APIs. Cloud APIs use serverless computing services, and choosing the right platform is crucial. Complexity, error handling, security, and optimization strategies need to be considered when handling XML parsing and PDF generation. The entire process requires the front-end app and the back-end API to work together, and it requires some understanding of a variety of technologies.

    How to convert xml into pictures How to convert xml into pictures Apr 03, 2025 am 07:39 AM

    XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

    Is there any mobile app that can convert XML into PDF? Is there any mobile app that can convert XML into PDF? Apr 02, 2025 pm 08:54 PM

    An application that converts XML directly to PDF cannot be found because they are two fundamentally different formats. XML is used to store data, while PDF is used to display documents. To complete the transformation, you can use programming languages ​​and libraries such as Python and ReportLab to parse XML data and generate PDF documents.

    See all articles