Path路径库好用工具 对比其他不同类型

本文详细介绍了Python标准库pathlib模块在处理文件路径、文件系统操作、类和方法、路径技巧以及示例应用,包括Path类的各种操作方法,如创建目录、文件操作、路径解析和通配符匹配等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#import os, sys
#base_dir = os.path.dirname(os.path.abspath(__file__))
# print(base_dir)
#sys.path.append(base_dir)
#当前运行文件路径

#项目根路径
#from pathlib import Path
#root_path_obj = Path(__file__).parent.parent.parent.parent.absolute()
#sys.path.append(str(root_path_obj))


# import platform
# if platform.system()=="Windows":
#     # 加载图片文件
#     img_file_path = Path(".//images//img.jpg")
# else:
#     img_file_path = Path(base_dir).joinpath("images", "img.jpg")


windows下路径:".//images//img.jpg"
centos下路径:"./images/img.jpg"
因不同系统下,路径格式不同,但通过Path工具可转换为兼容的格式

在Python中,pathlib模块提供了一种优雅而直观的方式来处理文件路径和文件系统操作。本文将深入探讨pathlib模块的使用方法、常用类和方法、路径操作技巧以及示例代码,帮助更好地理解和应用路径处理功能。

pathlib模块简介
pathlib模块是Python 3.4及以上版本中引入的标准库,用于处理文件路径和文件系统操作。它提供了一种面向对象的路径操作方式,使得代码更加清晰易读,并且避免了在不同操作系统下的路径分隔符问题。

常用类和方法
1. Path类
Path类是pathlib模块的核心,用于表示文件系统中的路径。

常用的方法包括:

Path.cwd(): 获取当前工作目录的Path对象。

Path.home(): 获取用户的主目录的Path对象。

Path.exists(): 判断路径是否存在。

Path.is_dir(): 判断路径是否是一个目录。

Path.is_file(): 判断路径是否是一个文件。

Path.glob(): 使用通配符匹配文件或目录。

2. Path操作方法
Path类还提供了丰富的路径操作方法,包括路径拼接、文件/目录创建、文件/目录移动/删除等操作。

示例代码如下:

from pathlib import Path
 
# 创建目录和文件
new_dir = Path('new_directory')
new_dir.mkdir()
new_file = new_dir / 'new_file.txt'
new_file.write_text('Hello, pathlib!')
 
# 移动文件
moved_file = new_dir / 'moved_file.txt'
new_file.rename(moved_file)
 
# 删除目录及其内容
new_dir.rmdir()
路径操作技巧
1. 使用resolve()方法解析路径
Path类的resolve()方法可以解析路径中的符号链接(软链接),获取真实的路径。

示例代码如下:

from pathlib import Path
 
# 创建软链接
source_file = Path('source_file.txt')
source_file.touch()
link_file = Path('link_file.txt')
link_file.symlink_to(source_file)
 
# 解析路径
resolved_path = link_file.resolve()
print("软链接解析后的真实路径:", resolved_path)
2. 使用glob()方法批量操作文件
Path类的glob()方法可以使用通配符匹配文件或目录,进行批量操作。

示例代码如下:

from pathlib import Path
 
# 使用glob匹配文件
for file in Path.cwd().glob('*.txt'):
    print("匹配到的文件:", file)
实际应用示例
示例一:查找指定文件类型并复制到指定目录
from pathlib import Path
import shutil
 
# 源目录和目标目录
source_dir = Path('source_directory')
target_dir = Path('target_directory')
 
# 创建目标目录
target_dir.mkdir(exist_ok=True)
 
# 查找指定类型的文件并复制到目标目录
for file in source_dir.glob('*.txt'):
    target_file = target_dir / file.name
    shutil.copy(file, target_file)
    print(f"复制文件 {file.name} 到目标目录")
这个示例演示了如何使用pathlib模块和shutil模块来查找源目录中特定类型的文件(例如.txt文件),然后将它们复制到目标目录。

示例二:遍历目录并删除指定文件
from pathlib import Path
 
# 目标目录
target_dir = Path('target_directory')
 
# 遍历目录并删除指定文件
for file in target_dir.glob('*.tmp'):
    file.unlink()
    print(f"删除文件 {file.name}")
这个示例展示了如何使用pathlib模块遍历目录,并删除目标目录中特定类型的文件(例如.tmp文件)。

示例三:计算目录中所有文件的总大小
from pathlib import Path
 
# 目标目录
target_dir = Path('target_directory')
 
# 初始化总文件大小计数器
total_size = 0
 
# 计算目录中所有文件的总大小
for file in target_dir.glob('*'):
    if file.is_file():
        total_size += file.stat().st_size
 
print(f"目录中所有文件的总大小为: {total_size} 字节")
这个示例展示了如何使用pathlib模块计算目录中所有文件的总大小,并输出总大小的字节数。
————————————————

                            版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
                        
原文链接:https://blog.youkuaiyun.com/GitHub_miao/article/details/137254302

参考源文 

https://www.jb51.net/article/213421.htm

一、Path 是什么?

该模块提供表示文件系统路径的类,其语义适用于不同的操作系统。路径类被分为提供纯计算操作而没有 I/O 的 纯路径,以及从纯路径继承而来但提供 I/O 操作的 具体路径。

在这里插入图片描述

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

  • 如果你想要在 Unix 设备上操作 Windows 路径(或者相反)。你不应在 Unix 上实例化一个 WindowsPath,但是你可以实例化 PureWindowsPath。
  • 你只想操作路径但不想实际访问操作系统。在这种情况下,实例化一个纯路径是有用的,因为它们没有任何访问操作系统的操作。

二、使用步骤

1.提取文件名

方法名 : .name

1

2

3

4

5

from pathlib import Path

path_str = Path(r"/usr/HinGwenWoong/demo.py")

path_file_name = path_str.name

print(path_file_name)

输出

demo.py

2.提取父文件路径

方法名 : .parent

1

2

3

4

5

from pathlib import Path

path_str = Path(r"/usr/HinGwenWoong/demo.py")

path_parent_path = path_str.parent

print(path_parent_path)

输出

\user\HinGwenWoong

3.提取文件后缀

方法名 : .suffix

1

2

3

4

5

from pathlib import Path

path_str = Path(r"/usr/HinGwenWoong/demo.py")

path_suffix = path_str.suffix

print(path_suffix)

输出

.py

4.提取无后缀的文件名

方法名 : .stem

1

2

3

4

5

from pathlib import Path

path_str = Path(r"/usr/HinGwenWoong/demo.py")

path_only_name = path_str.stem

print(path_only_name )

输出

demo

5.更改文件后缀

方法名 : .with_suffix

1

2

3

4

5

from pathlib import Path

path_str = Path(r"/usr/HinGwenWoong/demo.py")

path_suffix = path_str.with_suffix(".json")

print(path_suffix)

输出

\user\HinGwenWoong\demo.json

6.遍历文件

方法名 : .iterdir()

1

2

3

4

5

from pathlib import Path

path_str = Path(r"/usr/HinGwenWoong/logs")

for path in path_str.iterdir():

    print(path)

输出

/user/HinGwenWoong/log/20210517.log
/user/HinGwenWoong/log/20210518.log
/user/HinGwenWoong/log/20210519.log
/user/HinGwenWoong/log/20210524.log
/user/HinGwenWoong/log/20210525.log

7.组合文件路径

方法名 : .joinpath

1

2

3

4

5

from pathlib import Path

path_str = Path(r"/usr/HinGwenWoong/")

path_str_join = path_str.joinpath("demo.py")

print(path_str_join)

输出

\user\HinGwenWoong\demo.py

8.是否绝对路径

方法名 : is_absolute()

1

2

3

4

from pathlib import Path

path_str = Path(r"/usr/HinGwenWoong/")

print(path_str.is_absolute())

输出

True

9.是否文件夹 or 文件

方法名 : is_dir()、 is_file()

1

2

3

4

5

from pathlib import Path

path_str = Path(r"/usr/HinGwenWoong/")

print(path_str.is_dir())

print(path_str.is_file())

输出

True
False

10.是否存在

方法名 : .exists()

1

2

3

4

from pathlib import Path

path_str = Path(r"/usr/HinGwenWoong/")

print(path_str.exists())

输出

True

11.glob

方法名 : .glob

1

2

3

4

from pathlib import Path

path_str = Path(r"/user/HinGwenWoong/scripts")

print(path_str.glob('*.py'))

输出

[PosixPath('/user/HinGwenWoong/scripts/demo_1.py'),
PosixPath('/user/HinGwenWoong/scripts/demo_2.py')]

 Python路径操作库pathlib,比os+glob+shutil更好用_python pathlib-优快云博客

对应关系

功能    os 和 os.path    pathlib
绝对路径    os.path.abspath()    Path.resolve()
改变文件的模式和权限    os.chmod()    Path.chmod()
新建目录    os.mkdir()    Path.mkdir()
新建目录    os.makedirs()    Path.mkdir()
重命名    os.rename()    Path.rename()
覆盖    os.replace()    Path.replace()
删除目录    os.rmdir()    Path.rmdir()
移除此文件或符号链接    os.remove(), os.unlink()    Path.unlink()
当前工作目录    os.getcwd()    Path.cwd()
是否存在路径    os.path.exists()    Path.exists()
根目录    os.path.expanduser()    Path.expanduser() 和 Path.home()
列出路径下的文件和目录    os.listdir()    Path.iterdir()
是否为目录    os.path.isdir()    Path.is_dir()
是否为文件    os.path.isfile()    Path.is_file()
是否指向符号链接    os.path.islink()    Path.is_symlink()
创建硬链接    os.link()    Path.link_to()
将此路径创建为符号链接    os.symlink()    Path.symlink_to()
返回符号链接所指向的路径    os.readlink()    Path.readlink()
返回 os.stat_result 对象包含此路径信息    os.stat()    Path.stat(), Path.owner(), Path.group()
是否为绝对路径    os.path.isabs()    PurePath.is_absolute()
连接路径    os.path.join()    PurePath.joinpath()
文件名或目录名    os.path.basename()    PurePath.name
父目录    os.path.dirname()    PurePath.parent
是否相同文件    os.path.samefile()    Path.samefile()
文件名后缀    os.path.splitext()    PurePath.suffix
移动文件    shutil.move()    Path.rename()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值