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']
>>> 
目录
相关文章
|
9天前
|
XML JSON 数据库
Python的标准库
Python的标准库
121 77
|
15天前
|
Python
Python中的函数是**一种命名的代码块,用于执行特定任务或计算
Python中的函数是**一种命名的代码块,用于执行特定任务或计算
42 18
|
7天前
|
数据可视化 DataX Python
Seaborn 教程-绘图函数
Seaborn 教程-绘图函数
38 8
|
10天前
|
XML JSON 数据库
Python的标准库
Python的标准库
38 11
|
10天前
|
数据可视化 Python
以下是一些常用的图表类型及其Python代码示例,使用Matplotlib和Seaborn库。
通过这些思维导图和分析说明表,您可以更直观地理解和选择适合的数据可视化图表类型,帮助更有效地展示和分析数据。
50 8
|
16天前
|
Python
Python中的函数
Python中的函数
31 8
|
18天前
|
安全 API 文件存储
Yagmail邮件发送库:如何用Python实现自动化邮件营销?
本文详细介绍了如何使用Yagmail库实现自动化邮件营销。Yagmail是一个简洁强大的Python库,能简化邮件发送流程,支持文本、HTML邮件及附件发送,适用于数字营销场景。文章涵盖了Yagmail的基本使用、高级功能、案例分析及最佳实践,帮助读者轻松上手。
29 4
|
7月前
|
算法 Python 容器
Python编程 - 不调用相关choose库函数,“众数“挑选器、随机挑选器 的源码编程实现
Python编程 - 不调用相关choose库函数,“众数“挑选器、随机挑选器 的源码编程实现
96 0
|
3月前
|
算法 Python
Python编程的函数—内置函数
Python编程的函数—内置函数
22 0
|
7月前
|
算法 Python
Python编程实验四:函数的使用
Python编程实验四:函数的使用
107 0
下一篇
DataWorks