Home  >  Article  >  Backend Development  >  How to handle file paths using Python's pathlib module?

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

PHPz
PHPzforward
2023-04-21 13:34:171288browse

    1. 为什么需要pathlib

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

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

     如以上代码, 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'

    但是路径并不只是一个字符串,  如果需要对文件进行操作,  需要结合使用多个标准库的功能, 如: 需要移动当前目录下的一些文件到备份目录, 需要使用 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)

     有了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')

    另外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')

    另外 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')

    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')

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

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

    对于简单的文件读写, 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'

    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')

    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)

    如果需要重命名文件或者拓展名, 可以使用 .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')

    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')

    在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:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete