pathlib.Path 与 os.path

1、调用库
from pathlib import Path

2、创建path对象
p = Path(file)

3、方法总结
p.cwd() # 获取当前路径
 
p.stat()  # 获取当前文件的信息
 
p.exists()  # 判断当前路径是否是文件或者文件夹
 
p.glob(filename)  # 获取路径下的所有符合filename的文件,返回一个generator
 
p.rglob(filename)  # 与上面类似,只不过是返回路径中所有子文件夹的符合filename的文件
 
p.is_dir()  # 判断该路径是否是文件夹
 
p.is_file()  # 判断该路径是否是文件
 
p.iterdir()  #当path为文件夹时,通过yield产生path文件夹下的所有文件、文件夹路径的迭代器
 
P.mkdir(parents=Fasle)  # 根据路径创建文件夹,parents=True时,会依次创建路径中间缺少的文件夹
p_news = p/'new_dirs/new_dir'
p_news.mkdir(parents=True)
  
P.open(mode=’r’, buffering=-1, encoding=None, errors=None, newline=None)  #类似于open()函数
  
p.rename(target)  # 当target是string时,重命名文件或文件夹;当target是Path时,重命名并移动文件或文件夹
  
p.replace(target)  # 重命名当前文件或文件夹,如果target所指示的文件或文件夹已存在,则覆盖原文件
  
p.parent(),p.parents()  # parent获取path的上级路径,parents获取path的所有上级路径
  
p.is_absolute()  # 判断path是否是绝对路径
  
p.match(pattern)  # 判断path是否满足pattern
  
p.rmdir()  # 当path为空文件夹的时候,删除该文件夹
  
p.name  # 获取path文件名
  
p.suffix  # 获取path文件后缀

获取目录

from pathlib import Path
currentPath = Path.cwd()
homePath = Path.home()
print("文件当前所在目录:%s\n用户主目录:%s" %(currentPath, homePath))

目录拼接

斜杠 / 操作符用于拼接路径,比如创建子路径

from pathlib import Path
currentPath = Path.cwd()
newPath = currentPath / 'python-100'
print("新目录为:%s" %(newPath))

创建、删除目录

from pathlib import Path
currentPath = Path.cwd()
makePath = currentPath / 'python-100'
makePath.mkdir()
print("创建的目录为:%s" %(nmakePath))


from pathlib import Path
currentPath = Path.cwd()
delPath = currentPath / 'python-100'
delPath.rmdir()
print("删除的目录为:%s" %(delPath))

读写文件

Path.open(mode=’r’),以 “r” 格式打开 Path 路径下的文件,若文件不存在即创建后打开。
Path.read_bytes(),打开 Path 路径下的文件,以字节流格式读取文件内容,等同 open 操作文件的 “rb” 格式。
Path.read_text(),打开 Path 路径下的文件,以 str 格式读取文件内容,等同 open 操作文件的 “r” 格式。
Path.write_bytes(),对 Path 路径下的文件进行写操作,等同 open 操作文件的 “wb” 格式。
Path.write_text(),对 Path 路径下的文件进行写操作,等同 open 操作文件的 “w” 格式。
from pathlib import Path
currentPath = Path.cwd()
mkPath = currentPath / 'python-100.txt'
with mkPath.open('w') as f:  # 创建并以 "w" 格式打开 python-100.txt 文件。
    f.write('python-100')  # 写入 python-100 字符串。
f = open(mkPath, 'r')
print("读取的文件内容为:%s" % f.read())
f.close()

from pathlib import Path
currentPath = Path.cwd()
mkPathText = currentPath / 'python-100-text.txt'
mkPathText.write_text('python-100')
print("读取的文件内容为:%s" % mkPathText.read_text())

str2byte = bytes('python-100', encoding = 'utf-8')
mkPathByte = currentPath / 'python-100-byte.txt'
mkPathByte.write_bytes(str2byte)
print("读取的文件内容为:%s" % mkPathByte.read_bytes())

获取文件所在目录的不同部分字段

Path.resolve(),通过传入文件名,返回文件的完整路径。
Path.name,可以获取文件的名字,包含后缀名。
Path.parent,返回文件所在文件夹的名字。
Path.stem,获取文件名不包含后缀名。
Path.suffix,获取文件的后缀名。
Path.anchor,获取文件所在的盘符。
from pathlib import Path
txtPath = Path('python-100.txt')
nowPath = txtPath.resolve()
print("文件的完整路径为:%s" % nowPath)
print("文件完整名称为(文件名+后缀名):%s" % nowPath.name)
print("文件名为:%s" % nowPath.stem)
print("文件后缀名为:%s" % nowPath.suffix)
print("文件所在的文件夹名为:%s" % nowPath.parent)
print("文件所在的盘符为:%s" % nowPath.anchor)

文件、路径是否存在判断

Path.exists(),判断 Path 路径是否指向一个已存在的文件或目录,返回 True 或 False。
Path.is_dir(),判断 Path 是否是一个路径,返回 True 或 False。
Path.is_file(),判断 Path 是否指向一个文件,返回 True 或 False。
from pathlib import Path
currentPath = Path.cwd() / 'python'

print(currentPath.exists())  # 判断是否存在 python 文件夹,此时返回 False。
print(currentPath.is_dir())  # 判断是否存在 python 文件夹,此时返回 False。

currentPath.mkdir()  # 创建 python 文件夹。

print(currentPath.exists())  # 判断是否存在 python 文件夹,此时返回 True。
print(currentPath.is_dir())  # 判断是否存在 python 文件夹,此时返回 True。

currentPath = Path.cwd() / 'python-100.txt'

print(currentPath.exists())  # 判断是否存在 python-100.txt 文件,此时文件未创建返回 False。
print(currentPath.is_file())  # 判断是否存在 python-100.txt 文件,此时文件未创建返回 False。

f = open(currentPath,'w')  # 创建 python-100.txt 文件。
f.close()

print(currentPath.exists())  # 判断是否存在 python-100.txt 文件,此时返回 True。
print(currentPath.is_file())  # 判断是否存在 python-100.txt 文件,此时返回 True。

文件统计以及匹配查找

Path.iterdir(),返回 Path 目录文件夹下的所有文件,返回的是一个生成器类型。
Path.glob(pattern),返回 Path 目录文件夹下所有与 pattern 匹配的文件,返回的是一个生成器类型。
Path.rglob(pattern),返回 Path 路径下所有子文件夹中与 pattern 匹配的文件,返回的是一个生成器类型。
使用 Path.iterdir() 获取当前文件下的所有文件,并根据后缀名统计其个数。
import pathlib
from collections import Counter
currentPath = pathlib.Path.cwd()
gen = (i.suffix for i in currentPath.iterdir())
print(Counter(gen))

import pathlib
from collections import Counter
currentPath = pathlib.Path.cwd()
gen = (i.suffix for i in currentPath.glob('*.txt'))  # 获取当前文件下的所有 txt 文件,并统计其个数。
print(Counter(gen))
gen = (i.suffix for i in currentPath.rglob('*.txt'))  # 获取目录中子文件夹下的所有 txt 文件,并统计其个数。
print(Counter(gen))

路径拼接

旧的解决方式:os.path模块

import os.path

data_folder = os.path.join("source_data", "text_files")

file_to_open = os.path.join(data_folder, "raw_data.txt")

f = open(file_to_open)

print(f.read())

此代码可以在各个平台顺利运行,但是反复使用os.path.join很啰嗦,重点是一点都不优雅!

os.path有很多功能,但是比较繁琐,导致大家虽然都知道,但是就是懒得用。
更好解决方式:pathlib模块

python3.4+ 都自带标准库pathlib,所以你不需要再通过pip3 安装,这很cool

你只需要这样

from pathlib import Path

data_folder = Path("source_data/text_files/")

file_to_open = data_folder / "raw_data.txt"

f = open(file_to_open)

print(f.read())

至此,你用一个非常优雅的方式解决了一个重大问题,但是你以为pathlib仅此而已了吗?

你可用它读文件,而不需要open()

from pathlib import Path

data_folder = Path("source_data/text_files/")

file_to_open = data_folder / "raw_data.txt"

print(file_to_open.read_text())

更cool的是,pathlib可以让你常用的文件及路径操作变得极为简单快捷

from pathlib import Path

filename = Path("source_data/text_files/raw_data.txt")

print(filename.name)
# prints "raw_data.txt"

print(filename.suffix)
# prints "txt"

print(filename.stem)
# prints "raw_data"

if not filename.exists():
    print("Oops, file doesn't exist!")
else:
    print("Yay, the file exists!")

os.path.abspath
在这里插入图片描述

参考(感谢)
http://www.ityouknow.com/python/2019/10/19/python-pathlib-035.html
https://www.cnblogs.com/huwang-sun/p/12087850.html
https://zhuanlan.zhihu.com/p/33524938

  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值