当前完整路径_Pytorch 73.Python丝滑的路径处理库pathlib模块

本文介绍了Python 3.4及以上版本中pathlib模块如何简化文件路径操作,对比os.path,并展示了pathlib的面向对象特性、路径操作、文件名处理、路径拼接、文件操作和目录管理等高级功能。
摘要由CSDN通过智能技术生成

59e75df9764c957261129b2f7e12adba.png

使用 Python 操作文件路径,之前常用的做法是os.path。在 Python 3.4 之前和路径相关操作函数都放在 os 模块里面,尤其是os.path这个子模块,可以说os.path模块非常常用。而在 Python 3.4,标准库添加了新的模块 - pathlib,它使用面向对象的编程方式来表示文件系统路径。

科技猛兽:PyTorch 66.Python中的os.path 与sys.path​zhuanlan.zhihu.com
937898276e70a7d224aed02e2c58be29.png

Python 3.4以上的工程建议使用pathlib,相比于老式的 os.path 有几个优势:

  • 老用法在处理不同操作系统 win,mac 以及 linux 之间很吃力。换了操作系统常常要改代码,还经常需要进行一些额外操作。
  • 老用法主要是函数形式,返回的数据类型通常是字符串。但是路径和字符串并不等价,所以在使用 os 操作路径的时候常常还要引入其他类库协助操作。新用法是面向对象,处理起来更灵活方便。
  • Python3的系统标准库pathlib模块的 Path 对路径的操作会更简单。
下面的所有的例子中都把pathlib模块换为了pathlib2模块,pathlib2是以修补更新的pathlib2而发布的,所有的新功能都可以兼容过去的旧版本python。

首先是和 os 功能对应的方法列表:

先看一下 os (os.path) 模块里部分函数与pathlib.Path对应的方法吧。下面列出的这些可以直接用 pathlib 里面的用法代替:

os and os.pathpathlib
os.path.abspathPath.resolve
os.chmodPath.chmod
os.mkdirPath.mkdir
os.renamePath.rename
os.replacePath.replace
os.rmdirPath.rmdir
os.remove, os.unlinkPath.unlink
os.getcwdPath.cwd
os.path.existsPath.exists
os.path.expanduserPath.expanduser
os.path.isdirPath.is_dir
os.path.isfilePath.is_file
os.path.islinkPath.is_symlink
os.statPath.stat, Path.owner, Path.group
os.path.isabsPurePath.is_absolute
os.path.joinPurePath.joinpath
os.path.basenamePurePath.name
os.path.dirnamePurePath.parent
os.path.samefilePath.samefile
os.path.splitextPurePath.suffix

举 4 个例子:

# 原来的写法
In : os.path.isdir(os.getcwd())
Out: True
# 新的写法
In : Path.cwd().is_dir()
Out: True

# 原来的写法
In : os.path.basename('/usr/local/etc/mongod.conf')
Out: 'mongod.conf'
# 新的写法
In : Path('/usr/local/etc/mongod.conf').name
Out: 'mongod.conf'


pathlib.Path.home() / 'python' / 'scripts' / 'test.py'
# PosixPath('/home/gahjelle/python/scripts/test.py')

pathlib.Path.home().joinpath('python', 'scripts', 'test.py')
# PosixPath('/home/gahjelle/python/scripts/test.py')

接着感受下 pathlib 带来的变化。

获取当前目录

假设你的代码在 /home/dog1/dog2/DOG
from pathlib2 import Path

# 获取当前目录
current_path = Path.cwd()
print(current_path)

# 输出如下:
# /home/dog1/dog2/DOG

# 获取Home目录
home_path = Path.home()
print(home_path)
# 输出如下:
# /home/dog1

父目录操作

你可以看到想要获取一个路径下上级的父目录可以非常方便的直接使用面向对象的方式 .parent 就行了,如果还想上一级就继续以子对象继续操作parent属性就可以了。

from pathlib2 import Path

# 获取当前目录
current_path = Path.cwd()

# 获取上级父目录
print(current_path.parent)

# 获取上上级父目录
print(current_path.parent.parent)

# 获取上上上级父目录
print(current_path.parent.parent.parent)

# 获取上上上上级父目录
print(current_path.parent.parent.parent.parent)

# 获取上上上上级父目录
print(current_path.parent.parent.parent.parent.parent)

# 输出如下:
/home/dog1/dog2
/home/dog1
/home
/
/

当然路径是十分长的,而且在特定的场合我如果想获得每一级的父目录呢,贴心的pathlib已经帮我们想到了,使用parents属性就可以遍历整个父目录了,如下例子的效果和上面的例子是完全一样的,但是就变的非常简便。

# 获取当前目录
from pathlib2 import Path

current_path = Path.cwd()

for p in current_path.parents:
    print(p)

# 输出如下:
/home/dog1/dog2
/home/dog1
/home
/

文件名操作

常用的文件名操作属性如下:

  • name 目录的最后一个部分。
  • suffix 目录中最后一个部分的扩展名。
  • suffixes 返回多个扩展名列表。
  • stem 目录最后一个部分,没有后缀。
  • with_name(name) 替换目录最后一个部分并返回一个新的路径。
  • with_suffix(suffix) 替换扩展名,返回新的路径,扩展名存在则不变。
from pathlib2 import Path

# 返回目录中最后一个部分的扩展名
example_path = Path('/Users/Anders/Documents/abc.gif')
print(example_path.suffix)
# 输出如下:
# .gif

# 返回目录中多个扩展名列表
example_paths = Path('/Users/Anders/Documents/abc.tar.gz')
print(example_paths.suffixes)
# 输出如下:
# ['.tar', '.gz']

# 返回目录中最后一个部分的文件名(但是不包含后缀)
example_path = Path('/Users/Anders/Documents/abc.gif')
print(example_path.stem)
# 输出如下:
# abc

# 返回目录中最后一个部分的文件名
example_path = Path('/Users/Anders/Documents/abc.gif')
print(example_path.name)
# 输出如下:
# abc.gif

# 替换目录最后一个部分的文件名并返回一个新的路径
new_path1 = example_path.with_name('def.gif')
print(new_path1)
# 输出如下:
# /Users/Anders/Documents/def.gif

# 替换目录最后一个部分的文件名并返回一个新的路径
new_path2 = example_path.with_suffix('.txt')
print(new_path2)
# 输出如下:
# /Users/Anders/Documents/abc.txt
In : base = os.path.basename('/usr/local/etc/my.cnf')

In : base
Out: 'my.cnf'

In : stem, suffix = os.path.splitext(base)

In : stem, suffix
Out: ('my', '.cnf')

In : p = Path('/usr/local/etc/my.cnf')

In : p.suffix, p.stem
Out: ('.cnf', 'my')

路径拼接和分解

pathlib 支持用/拼接路径。如果用不惯/,也可以用类似 os.path.join 的方法:

from pathlib2 import Path

#直接传进一个完整字符串
example_path1 = Path('/Users/Anders/Documents/powershell-2.jpg')

#也可以传进多个字符串
example_path2 = Path('/', 'Users', 'dongh', 'Documents', 'python_learn', 'pathlib_', 'file1.txt')

#也可以利用Path.joinpath()
example_path3 = Path('/Users/Anders/Documents/').joinpath('python_learn')

# #利用 / 可以创建子路径
example_path4 = Path('/Users/Anders/Documents')
example_path5 = example_path4 / 'python_learn/pic-2.jpg'

遍历文件夹

我们可以在路径对象后面直接使用 iterdir()方法,该方法返回一个生成器,我们可以循环遍历出所有指定目录下的目录路径。

from pathlib2 import Path

# 返回目录中最后一个部分的扩展名
example_path = Path('/Users/Anders/Documents')
[path for path in example_path.iterdir()]

# 输出如下:
# [PosixPath('/Users/Anders/Documents/abc.jpg'),
#  PosixPath('/Users/Anders/Documents/book-master'),
#  PosixPath('/Users/Anders/Documents/Database'),
#  PosixPath('/Users/Anders/Documents/Git'),
#  PosixPath('/Users/Anders/Documents/AppProjects')]

文件操作

文件操作是使用率非常高的操作,在pathlib里如果要打开一个文件也十分的简单,只需要open方法就可以,它的操作语法是:open(mode=‘r’, bufferiong=-1, encoding=None, errors=None, newline=None)

from pathlib2 import Path

example_path = Path('/Users/Anders/Documents/information/JH.txt')

with example_path.open(encoding = 'GB2312') as f:
    print(f.read())

对于简单的文件读写,在pathlib库中有几个简便的方法:

  • .read_text(): 以文本模式打开路径并并以字符串形式返回内容。
  • .read_bytes(): 以二进制/字节模式打开路径并以字节串的形式返回内容。
  • .write_text(): 打开路径并向其写入字符串数据。
  • .write_bytes(): 以二进制/字节模式打开路径并向其写入数据。

比如可以把之前的例子改写如下:

from pathlib2 import Path

example_path = Path('/Users/Anders/Documents/information/JH.txt')
example_path.read_text(encoding='GB2312')

创建文件夹和删除文件夹

关于这里的创建文件目录mkdir方法接收两个参数:

  • parents:如果父目录不存在,是否创建父目录。
  • exist_ok:只有在目录不存在时创建目录,目录已存在时不会抛出异常。
from pathlib2 import Path

example_path = Path('/Users/Anders/Documents/test1/test2/test3')

# 创建文件目录,在这个例子中因为本身不存在test1,test2,test3,由于parents为True,所以都会被创建出来。
example_path.mkdir(parents = True, exist_ok = True)
# 删除路径对象目录,如果要删除的文件夹内包含文件就会报错
example_path.rmdir()

判断文件及文件夹对象是否存在

关于文件的判断还有很多相关属性,罗列如下:

  • is_dir() 是否是目录
  • is_file() 是否是普通文件
  • is_symlink() 是否是软链接
  • is_socket() 是否是socket文件
  • is_block_device() 是否是块设备
  • is_char_device() 是否是字符设备
  • is_absolute() 是否是绝对路径
  • resolve() 返回一个新的路径,这个新路径就是当前Path对象的绝对路径,如果是软链接则直接被解析
  • absolute() 也可以获取绝对路径,但是推荐resolve()
  • exists() 该路径是否指向现有的目录或文件:

部分例子可以参照下面:

from pathlib2 import Path

example_path = Path('/Users/Anders/Documents/pic-2.jpg')

# 判断对象是否存在
print(example_path.exists())
# 输出如下:
# True

# 判断对象是否是目录
print(example_path.is_dir())
# 输出如下:
# False

# 判断对象是否是文件
print(example_path.is_file())
# 输出如下:
# True

文件的信息

只需要通过**.stat()**方法就可以返还指定路径的文件信息。

from pathlib2 import Path

example_path = Path('/Users/Anders/Documents/pic.jpg')
print(example_path.stat())
# 输出如下:
# os.stat_result(st_mode=33188, st_ino=8598206944, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=38054, st_atime=1549547190, st_mtime=1521009880, st_ctime=1521009883)

print(example_path.stat().st_size)
# 输出如下:
# 38054

参考:

你应该使用pathlib替代os.path​www.dongwm.com
42a70661032bdef41531bc6abaf31b90.png
第35天:pathlib 模块 - 纯洁的微笑博客​www.ityouknow.com Python基础学习:pathlib模块_zhtysw的博客-CSDN博客_pathlib模块​blog.csdn.net
09fbed6c1fbbba2e8733661607ca9206.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值