python中pathlib模块的基本⽤法与总结
前⾔
相⽐常⽤的 os.path⽽⾔,pathlib 对于⽬录路径的操作更简介也更贴近 Pythonic。但是它不单纯是为了简化操作,还有更⼤的⽤途。
pathlib 是Python内置库,Python ⽂档给它的定义是:The pathlib module – object-oriented filesystem paths(⾯向对象的⽂件系统路径)。pathlib 提供表⽰⽂件系统路径的类,其语义适⽤于不同的操作系统。
1. pathlib模块下Path类的基本使⽤
from pathlib import Path
path = r'D:\python\pycharm2020\program\pathlib模块的基本使⽤.py'
p = Path(path)
print(p.name) # 获取⽂件名
print(p.stem) # 获取⽂件名除后缀的部分
print(p.suffix) # 获取⽂件后缀
print(p.parent) # 相当于dirname
print(p.parent.parent.parent)
print(p.parents) # 返回⼀个iterable 包含所有⽗⽬录
for i in p.parents:
print(i)
print(p.parts) # 将路径通过分隔符分割成⼀个元组
运⾏结果如下:
pathlib模块的基本使⽤.py
pathlib模块的基本使⽤
.py
D:\python\pycharm2020\program
D:\python
<WindowsPath.parents>
D:\python\pycharm2020\program
D:\python\pycharm2020exists的用法
D:\python
D:\
('D:\\', 'python', 'pycharm2020', 'program', 'pathlib模块的基本使⽤.py')
Path.cwd():Return a new path object representing the current directory
Path.home():Return a new path object representing the user's home directory
from pathlib import Path
path_1 = Path.cwd() # 获取当前⽂件路径
path_2 = Path.home()
p1 = Path('~/pathlib模块的基本使⽤.py')
print(path_1)
print(path_2)
panduser())
运⾏结果如下:
D:\python\pycharm2020\program
C:\Users\Administrator
C:\Users\Administrator\pathlib模块的基本使⽤.py
Path.stat():Return a os.stat_result object containing information about this path
from pathlib import Path
import datetime
p = Path('pathlib模块的基本使⽤.py')
print(p.stat()) # 获取⽂件详细信息
print(p.stat().st_size) # ⽂件的字节⼤⼩
print(p.stat().st_ctime) # ⽂件创建时间
print(p.stat().st_mtime) # 上次修改⽂件的时间
creat_time = datetime.datetime.fromtimestamp(p.stat().st_ctime)
st_mtime = datetime.datetime.fromtimestamp(p.stat().st_mtime)
print(f'该⽂件创建时间:{creat_time}')
print(f'上次修改该⽂件的时间:{st_mtime}')
运⾏结果如下:
os.stat_result(st_mode=33206, st_ino=3659174698076635, st_dev=3730828260, st_nlink=1, st_uid=0, st_gid=0, st_size=543, st_atime=1597366826, st_mtime=1597366826, st_ctime=1597320585)
543
1597320585.7657475
1597366826.9711637
该⽂件创建时间:2020-08-13 20:09:45.765748
上次修改该⽂件的时间:2020-08-14 09:00:26.971164
从不同.stat().st_属性返回的时间戳表⽰⾃1970年1⽉1⽇以来的秒数,可以⽤datetime.fromtimestamp将时间戳转换为有⽤的时间格式。
from pathlib import Path
p1 = Path('pathlib模块的基本使⽤.py') # ⽂件
p2 = Path(r'D:\python\pycharm2020\program') # ⽂件夹
absolute_path = p1.resolve()
print(absolute_path)
print(Path('.').exists())
ists(), p2.exists())
print(p1.is_file(), p2.is_file())
print(p1.is_dir(), p2.is_dir())
print(Path('/python').exists())
print(Path('non_existent_file').exists())
运⾏结果如下:
D:\python\pycharm2020\program\pathlib模块的基本使⽤.py
True
True True
True False
False True
True
False
Path.iterdir():When the path points to a directory,yield path objects of the directory contents
from pathlib import Path
p = Path('/python')
for child in p.iterdir():
print(child)
运⾏结果如下:
\python\Anaconda
\python\EVCapture
\python\Evernote_6.21.
\python\Notepad++
\python\pycharm-community-2020.
\python\pycharm2020
\python\pyecharts-assets-master
\python\pyecharts-gallery-master
\python\Sublime text 3
Path.glob(pattern):Glob the given relative pattern in the directory represented by this path, yielding all matching files (of any kind),The “**” pattern means “this directory and all subdirectories, recursively”. In other words, it enables recursive globbing. Note:Using the “**” pattern in large directory trees may consume an inordinate amount of time
递归遍历该⽬录下所有⽂件,获取所有符合pattern的⽂件,返回⼀个generator。
获取该⽂件⽬录下所有.py⽂件
from pathlib import Path
path = r'D:\python\pycharm2020\program'
p = Path(path)
file_name = p.glob('**/*.py')
print(type(file_name)) # <class 'generator'>
for i in file_name:
print(i)
获取该⽂件⽬录下所有.jpg图⽚
from pathlib import Path
path = r'D:\python\pycharm2020\program'
p = Path(path)
file_name = p.glob('**/*.jpg')
print(type(file_name)) # <class 'generator'>
for i in file_name:
print(i)
获取给定⽬录下所有.txt⽂件、.jpg图⽚和.py⽂件
from pathlib import Path
def get_files(patterns, path):
all_files = []
p = Path(path)
for item in patterns:
file_name = p.rglob(f'**/*{item}')
d(file_name)
return all_files
path = input('>>>请输⼊⽂件路径:')
results = get_files(['.txt', '.jpg', '.py'], path)
print(results)
for file in results:
print(file)
Path.mkdir(mode=0o777, parents=False, exist_ok=False)
Create a new directory at this given path. If mode is given, it is combined with the process' umask value to determine the file mode and access flags. If the path already exists, FileExistsError is raised.
If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command).
If parents is false (the default), a missing parent raises FileNotFoundError.
If exist_ok is false (the default), FileExistsError is raised if the target directory already exists.
If exist_ok is true, FileExistsError exceptions will be ignored (same behavior as the POSIX mkdir -p command), but only if the last path component is not an existing non-directory file.
Changed in version 3.5: The exist_ok parameter was added.
from pathlib import Path
p = Path(r'D:\python\pycharm2020\program\test')
p.mkdir()
from pathlib import Path
p = Path(r'D:\python\test1\test2\test3')
p.mkdir(parents=True) # If parents is true, any missing parents of this path are created as needed
from pathlib import Path
p = Path(r'D:\python\test1\test2\test3')
p.mkdir(exist_ok=True)
Path.unlink(missing_ok=False):Remove this file or symbolic link. If the path points to a directory, dir() instead. If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist. If missing_ok is true, FileNotFoundError exceptions will be ignored. Changed in version 3.8:The missing_ok parameter was added.
On Unix, if target exists and is a file, it will be replaced silently if the user has permission. target can be either a string or another path object.
Path.open(mode=‘r', buffering=-1, encoding=None, errors=None, newline=None):Open the file pointed to by the path, like the built-in open() function does.
from pathlib import Path
p = Path('')
p.open(mode='w').write('some text')
target = Path('')
content = target.open(mode='r').read()
print(content)
target.unlink()
2. 与os模块⽤法的对⽐
总结
到此这篇关于python中pathlib模块的基本⽤法与总结的⽂章就介绍到这了,更多相关python pathlib模块⽤法内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论