Python教程

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']

>>> 

 

这篇关于Python 路径库pathlib常用函数的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!