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



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.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

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.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.
