How to handle file paths using Python's pathlib module?
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 的 纯路径对象. 各个路径的关系如下:
在一些用例中纯路径很有用,例如:
如果你想要在 Unix 设备上操作 Windows 路径(或者相反)。你不应在 Unix 上实例化一个 WindowsPath,但是你可以实例化 PureWindowsPath。
你只想操作路径但不想实际访问操作系统。在这种情况下,实例化一个纯路径是有用的,因为它们没有任何访问操作系统的操作。
附: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中,是这样的
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

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 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 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.

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.

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.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

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".
