Python 路径库pathlib常用函数

简介: Python 路径库pathlib常用函数

除了os.path,模块pathlib也能对文件路径进行操作:

Python 3.8.8 (tags/v3.8.8:024d805, Feb 19 2021, 13:08:11) [MSC v.1928 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import pathlib
>>> dir(pathlib)
['EBADF', 'EINVAL', 'ELOOP', 'ENOENT', 'ENOTDIR', 'Path', 'PosixPath', 'PurePath', 
'PurePosixPath', 'PureWindowsPath', 'S_ISBLK', 'S_ISCHR', 'S_ISDIR', 'S_ISFIFO', 'S_ISLNK', 
'S_ISREG', 'S_ISSOCK', 'Sequence', 'WindowsPath', '_Accessor', '_Flavour', 
'_IGNORED_ERROS', '_IGNORED_WINERRORS', '_NormalAccessor', '_PathParents', '_PosixFlavour', 
'_PreciseSelector', '_RecursiveWildcardSelector', '_Selector', '_TerminatingSelector', 
'_WildcardSelector', '_WindowsFlavour', '__all__', '__builtins__', '__cached__', '__doc__', 
'__file__', '__loader__', '__name__', '__package__', '__spec__', '_getfinalpathname', 
'_ignore_error', '_is_wildcard_pattern', '_make_selector', '_normal_accessor', 
'_posix_flavour', '_windows_flavour', 'attrgetter', 'fnmatch', 'functools', 'io', 'nt', 
'ntpath', 'os', 'posixpath', 're', 'supports_symlinks', 'sys', 'urlquote_from_bytes']
>>> pathlib.__all__
['PurePath', 'PurePosixPath', 'PureWindowsPath', 'Path', 'PosixPath', 'WindowsPath']



此模块中共有6个类功能都差不多,以最后一个WindowsPath来举例:

>>> from pathlib import WindowsPath as wp
>>> dir(wp)
['__bytes__', '__class__', '__delattr__', '__dir__', '__doc__', '__enter__', '__eq__', 
'__exit__', '__format__', '__fspath__', '__ge__', '__getattribute__', '__gt__', 
'__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', 
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rtruediv__', '__setattr__', 
'__sizeof__', '__slots__', '__str__', '__subclasshook__', '__truediv__', '_accessor', 
'_cached_cparts', '_closed', '_cparts', '_drv', '_flavour', '_format_parsed_parts', 
'_from_parsed_parts', '_from_parts', '_hash', '_init', '_make_child', 
'_make_child_relpath', '_opener', '_parse_args', '_parts', '_pparts', '_raise_closed', 
'_raw_open', '_root', '_str', 'absolute', 'anchor', 'as_posix', 'as_uri', 'chmod', 'cwd', 
'drive', 'exists', 'expanduser', 'glob', 'group', 'home', 'is_absolute', 
'is_block_device', 'is_char_device', 'is_dir', 'is_fifo', 'is_file', 'is_mount', 
'is_reserved', 'is_socket', 'is_symlink', 'iterdir', 'joinpath', 'lchmod', 'link_to', 
'lstat', 'match', 'mkdir', 'name', 'open', 'owner', 'parent', 'parents', 'parts', 
'read_bytes', 'read_text', 'relative_to', 'rename', 'replace', 'resolve', 'rglob', 
'rmdir', 'root', 'samefile', 'stat', 'stem', 'suffix', 'suffixes', 'symlink_to', 'touch', 
'unlink', 'with_name', 'with_suffix', 'write_bytes', 'write_text']
>>> print(wp.__doc__)
Path subclass for Windows systems.
    On a Windows system, instantiating a Path should return this object.
>>> [i for i in dir(wp) if i[0]>='a']
['absolute', 'anchor', 'as_posix', 'as_uri', 'chmod', 'cwd', 'drive', 'exists', 
'expanduser', 'glob', 'group', 'home', 'is_absolute', 'is_block_device', 
'is_char_device', 'is_dir', 'is_fifo', 'is_file', 'is_mount', 'is_reserved', 'is_socket', 
'is_symlink', 'iterdir', 'joinpath', 'lchmod', 'link_to', 'lstat', 'match', 'mkdir', 
'name', 'open', 'owner', 'parent', 'parents', 'parts', 'read_bytes', 'read_text', 
'relative_to', 'rename', 'replace', 'resolve', 'rglob', 'rmdir', 'root', 'samefile', 
'stat', 'stem', 'suffix', 'suffixes', 'symlink_to', 'touch', 'unlink', 'with_name', 
'with_suffix', 'write_bytes', 'write_text']


对完整路径的分拆:

>>> p=r'd:\abc\exam\text1.doc'
>>> wp(p).anchor
'd:\\'
>>> wp(p).drive
'd:'
>>> wp(p).name
'text1.doc'
>>> wp(p).parent
WindowsPath('d:/abc/exam')
>>> str(wp(p).parent)
'd:\\abc\\exam'
>>> wp(p).parents
<WindowsPath.parents>
>>> wp(p).parts
('d:\\', 'abc', 'exam', 'text1.doc')
>>> wp(p).root
'\\'
>>> wp(p).stem
'text1'
>>> wp(p).suffix
'.doc'
>>> wp(p).suffixes
['.doc']
>>> 



其它函数:

>>> wp(p).cwd()
WindowsPath('D:/')
>>> str(wp(p).cwd())
'D:\\'
>>> wp(p).home()
WindowsPath('C:/Users/Administrator')
>>> str(wp(p).home())
'C:\\Users\\Administrator'
>>> wp(p).owner()
Traceback (most recent call last):
  File "<pyshell#50>", line 1, in <module>
    wp(p).owner()
  File "D:\Python38-32\lib\pathlib.py", line 1570, in owner
    raise NotImplementedError("Path.owner() is unsupported on this system")
NotImplementedError: Path.owner() is unsupported on this system
>>> # Windows不支持owner属性
>>> wp(p).exists()
True
>>> wp(p).is_dir()
False
>>> wp(p).is_file()
True
>>> 



完整帮助:

>>> help(pathlib.WindowsPath)
Help on class WindowsPath in module pathlib:
class WindowsPath(Path, PureWindowsPath)
 |  WindowsPath(*args, **kwargs)
 |  
 |  Path subclass for Windows systems.
 |  
 |  On a Windows system, instantiating a Path should return this object.
 |  
 |  Method resolution order:
 |      WindowsPath
 |      Path
 |      PureWindowsPath
 |      PurePath
 |      builtins.object
 |  
 |  Methods defined here:
 |  
 |  group(self)
 |      Return the group name of the file gid.
 |  
 |  is_mount(self)
 |      Check if this path is a POSIX mount point
 |  
 |  owner(self)
 |      Return the login name of the file owner.
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from Path:
 |  
 |  __enter__(self)
 |  
 |  __exit__(self, t, v, tb)
 |  
 |  absolute(self)
 |      Return an absolute version of this path.  This function works
 |      even if the path doesn't point to anything.
 |      
 |      No normalization is done, i.e. all '.' and '..' will be kept along.
 |      Use resolve() to get the canonical path to a file.
 |  
 |  chmod(self, mode)
 |      Change the permissions of the path, like os.chmod().
 |  
 |  exists(self)
 |      Whether this path exists.
 |  
 |  expanduser(self)
 |      Return a new path with expanded ~ and ~user constructs
 |      (as returned by os.path.expanduser)
 |  
 |  glob(self, pattern)
 |      Iterate over this subtree and yield all existing files (of any
 |      kind, including directories) matching the given relative pattern.
 |  
 |  is_block_device(self)
 |      Whether this path is a block device.
 |  
 |  is_char_device(self)
 |      Whether this path is a character device.
 |  
 |  is_dir(self)
 |      Whether this path is a directory.
 |  
 |  is_fifo(self)
 |      Whether this path is a FIFO.
 |  
 |  is_file(self)
 |      Whether this path is a regular file (also True for symlinks pointing
 |      to regular files).
 |  
 |  is_socket(self)
 |      Whether this path is a socket.
 |  
 |  is_symlink(self)
 |      Whether this path is a symbolic link.
 |  
 |  iterdir(self)
 |      Iterate over the files in this directory.  Does not yield any
 |      result for the special paths '.' and '..'.
 |  
 |  lchmod(self, mode)
 |      Like chmod(), except if the path points to a symlink, the symlink's
 |      permissions are changed, rather than its target's.
 |  
 |  link_to(self, target)
 |      Create a hard link pointing to a path named target.
 |  
 |  lstat(self)
 |      Like stat(), except if the path points to a symlink, the symlink's
 |      status information is returned, rather than its target's.
 |  
 |  mkdir(self, mode=511, parents=False, exist_ok=False)
 |      Create a new directory at this given path.
 |  
 |  open(self, mode='r', buffering=-1, encoding=None, errors=None, newline=None)
 |      Open the file pointed by this path and return a file object, as
 |      the built-in open() function does.
 |  
 |  read_bytes(self)
 |      Open the file in bytes mode, read it, and close the file.
 |  
 |  read_text(self, encoding=None, errors=None)
 |      Open the file in text mode, read it, and close the file.
 |  
 |  rename(self, target)
 |      Rename this path to the target path.
 |      
 |      The target path may be absolute or relative. Relative paths are
 |      interpreted relative to the current working directory, *not* the
 |      directory of the Path object.
 |      
 |      Returns the new Path instance pointing to the target path.
 |  
 |  replace(self, target)
 |      Rename this path to the target path, overwriting if that path exists.
 |      
 |      The target path may be absolute or relative. Relative paths are
 |      interpreted relative to the current working directory, *not* the
 |      directory of the Path object.
 |      
 |      Returns the new Path instance pointing to the target path.
 |  
 |  resolve(self, strict=False)
 |      Make the path absolute, resolving all symlinks on the way and also
 |      normalizing it (for example turning slashes into backslashes under
 |      Windows).
 |  
 |  rglob(self, pattern)
 |      Recursively yield all existing files (of any kind, including
 |      directories) matching the given relative pattern, anywhere in
 |      this subtree.
 |  
 |  rmdir(self)
 |      Remove this directory.  The directory must be empty.
 |  
 |  samefile(self, other_path)
 |      Return whether other_path is the same or not as this file
 |      (as returned by os.path.samefile()).
 |  
 |  stat(self)
 |      Return the result of the stat() system call on this path, like
 |      os.stat() does.
 |  
 |  symlink_to(self, target, target_is_directory=False)
 |      Make this path a symlink pointing to the given path.
 |      Note the order of arguments (self, target) is the reverse of os.symlink's.
 |  
 |  touch(self, mode=438, exist_ok=True)
 |      Create this file with the given access mode, if it doesn't exist.
 |  
 |  unlink(self, missing_ok=False)
 |      Remove this file or link.
 |      If the path is a directory, use rmdir() instead.
 |  
 |  write_bytes(self, data)
 |      Open the file in bytes mode, write to it, and close the file.
 |  
 |  write_text(self, data, encoding=None, errors=None)
 |      Open the file in text mode, write to it, and close the file.
 |  
 |  ----------------------------------------------------------------------
 |  Class methods inherited from Path:
 |  
 |  cwd() from builtins.type
 |      Return a new path pointing to the current working directory
 |      (as returned by os.getcwd()).
 |  
 |  home() from builtins.type
 |      Return a new path pointing to the user's home directory (as
 |      returned by os.path.expanduser('~')).
 |  
 |  ----------------------------------------------------------------------
 |  Static methods inherited from Path:
 |  
 |  __new__(cls, *args, **kwargs)
 |      Construct a PurePath from one or several strings and or existing
 |      PurePath objects.  The strings and path objects are combined so as
 |      to yield a canonicalized path, which is incorporated into the
 |      new PurePath object.
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from PurePath:
 |  
 |  __bytes__(self)
 |      Return the bytes representation of the path.  This is only
 |      recommended to use under Unix.
 |  
 |  __eq__(self, other)
 |      Return self==value.
 |  
 |  __fspath__(self)
 |  
 |  __ge__(self, other)
 |      Return self>=value.
 |  
 |  __gt__(self, other)
 |      Return self>value.
 |  
 |  __hash__(self)
 |      Return hash(self).
 |  
 |  __le__(self, other)
 |      Return self<=value.
 |  
 |  __lt__(self, other)
 |      Return self<value.
 |  
 |  __reduce__(self)
 |      Helper for pickle.
 |  
 |  __repr__(self)
 |      Return repr(self).
 |  
 |  __rtruediv__(self, key)
 |  
 |  __str__(self)
 |      Return the string representation of the path, suitable for
 |      passing to system calls.
 |  
 |  __truediv__(self, key)
 |  
 |  as_posix(self)
 |      Return the string representation of the path with forward (/)
 |      slashes.
 |  
 |  as_uri(self)
 |      Return the path as a 'file' URI.
 |  
 |  is_absolute(self)
 |      True if the path is absolute (has both a root and, if applicable,
 |      a drive).
 |  
 |  is_reserved(self)
 |      Return True if the path contains one of the special names reserved
 |      by the system, if any.
 |  
 |  joinpath(self, *args)
 |      Combine this path with one or several arguments, and return a
 |      new path representing either a subpath (if all arguments are relative
 |      paths) or a totally different path (if one of the arguments is
 |      anchored).
 |  
 |  match(self, path_pattern)
 |      Return True if this path matches the given pattern.
 |  
 |  relative_to(self, *other)
 |      Return the relative path to another path identified by the passed
 |      arguments.  If the operation is not possible (because this is not
 |      a subpath of the other path), raise ValueError.
 |  
 |  with_name(self, name)
 |      Return a new path with the file name changed.
 |  
 |  with_suffix(self, suffix)
 |      Return a new path with the file suffix changed.  If the path
 |      has no suffix, add given suffix.  If the given suffix is an empty
 |      string, remove the suffix from the path.
 |  
 |  ----------------------------------------------------------------------
 |  Readonly properties inherited from PurePath:
 |  
 |  anchor
 |      The concatenation of the drive and root, or ''.
 |  
 |  drive
 |      The drive prefix (letter or UNC path), if any.
 |  
 |  name
 |      The final path component, if any.
 |  
 |  parent
 |      The logical parent of the path.
 |  
 |  parents
 |      A sequence of this path's logical parents.
 |  
 |  parts
 |      An object providing sequence-like access to the
 |      components in the filesystem path.
 |  
 |  root
 |      The root of the path, if any.
 |  
 |  stem
 |      The final path component, minus its last suffix.
 |  
 |  suffix
 |      The final component's last suffix, if any.
 |      
 |      This includes the leading period. For example: '.txt'
 |  
 |  suffixes
 |      A list of the final component's suffixes, if any.
 |      
 |      These include the leading periods. For example: ['.tar', '.gz']
>>> 
目录
相关文章
|
1天前
|
机器学习/深度学习 算法 前端开发
2024年8个可以提高数据科学工作效率并节省宝贵时间的Python库,2024年最新记得把每一次面试当做经验积累
2024年8个可以提高数据科学工作效率并节省宝贵时间的Python库,2024年最新记得把每一次面试当做经验积累
2024年8个可以提高数据科学工作效率并节省宝贵时间的Python库,2024年最新记得把每一次面试当做经验积累
|
1天前
|
Linux C语言 iOS开发
Python初学者在不同系统上安装Python的保姆级指引_altinstall 安装路径
Python初学者在不同系统上安装Python的保姆级指引_altinstall 安装路径
|
3天前
|
程序员 开发者 Python
Python中的装饰器:优雅而强大的函数修饰工具
在Python编程中,装饰器是一种强大的工具,它可以简洁地实现函数的增强、扩展和重用。本文将深入探讨Python中装饰器的工作原理、常见应用场景以及如何自定义装饰器,帮助读者更好地理解和运用这一重要的编程概念。
|
3天前
|
网络安全 Python
vscode远程连接修改python解释器路径 - 蓝易云
以上就是在VSCode中修改Python解释器路径的步骤。希望这个指南能帮助你解决问题。
15 2
|
4天前
|
网络协议 数据处理 调度
深入探索Python异步编程:asyncio库的应用与实践
在现代软件开发中,异步编程已成为处理并发和I/O密集型任务的重要策略。本文将带您深入探索Python的asyncio库,解析其背后的设计原理,并通过实例展示如何在实际项目中应用asyncio实现高效的异步编程。我们不仅会探讨asyncio的基本用法,还会分析其性能优势,并探讨其与其他并发模型的比较。此外,文章还将涵盖asyncio在Web开发、网络编程和数据处理等场景中的应用案例,帮助您更好地理解并掌握这一强大的异步编程工具。
|
4天前
|
iOS开发 Python
mac:python安装路径,带你全面解析Python框架体系架构view篇
mac:python安装路径,带你全面解析Python框架体系架构view篇
|
4天前
|
数据采集 Python
10个Python set 常用操作函数!,bilibili面试题
10个Python set 常用操作函数!,bilibili面试题
10个Python set 常用操作函数!,bilibili面试题
|
4天前
|
数据采集 数据挖掘 Python
Python学习——函数,2024年最新手持4个大厂offer的我
Python学习——函数,2024年最新手持4个大厂offer的我
|
4天前
|
数据采集 数据挖掘 关系型数据库
Excel计算函数(计算机二级)(1),2024年最新2024Python架构面试指南
Excel计算函数(计算机二级)(1),2024年最新2024Python架构面试指南
|
4天前
|
存储 Java Shell
【Python学习教程】Python函数和lambda表达式_6(1),2024蚂蚁金服面试题及答案
【Python学习教程】Python函数和lambda表达式_6(1),2024蚂蚁金服面试题及答案