Pathlib is a better path library than OS

Public id: AI Yue Chuang, continue to update Python Office Automation

This module provides classes that represent file system paths with semantics suitable for different operating systems. Path classes are classified as providing pure computing operations without I/OPure path, and inherits from pure paths but provides I/O operationsThe specific path.If you’ve never used this module before, or if you’re not sure which class is appropriate for the task, this might be the one to usePath. It is instantiated on the platform on which the code is runningThe specific path.

Pure paths are useful in some use cases, such as:

  1. If you want to operate Windows paths on a Unix device (or vice versa). You should not instantiate a WindowsPath on Unix, but you can instantiate PureWindowsPath.

  2. You want to manipulate paths but not actually access the operating system. In this case, instantiating a pure path is useful because they don’t have any access to the operating system.

  3. Summary: Pure path only path, specific path depends on the operation.

Based on using

Import main class:

In [1] :from pathlib import Path
Copy the code

List subdirectories:

In [2]: p = Path(".")

In [3]: [x for x in p.iterdir() if x.is_dir()]
Out[3]:
[PosixPath('Chapter 4: Word Automation'),
 PosixPath('Chapter 5: PTT Automation'),
 PosixPath('Chapter 3: Excel Automation')]
Copy the code
  • Iterdir () : iterates through the files in this directory. For the special path “. And “..” Nothing will come of it.
  • **is_dir() : ** Whether this path is a directory.

List all Python source files under the current directory tree:

In [45] :list(p.glob('**/*.py'))
Out[45]:
[PosixPath('Chapter 5: PTT Automation /8.Python Generating Data GIFs /data_change_to_gif.py'),
 PosixPath('Chapter 3: Excel Automation /10. Multi-threaded Excel Pixel Drawing/excel_paint.py')]
Copy the code

Moving in a directory tree:

In [51]: p = Path('/etc')

In [52]: q = p / 'init.d' / 'reboot'

In [53]: q
Out[53]: PosixPath('/etc/init.d/reboot')

In [54]: q.resolve()
Out[54]: PosixPath('/private/etc/init.d/reboot')
Copy the code

To query the properties of a path:

In [61]: p = Path(".")

In [62]: p.exists() # Does this path point to an existing file or directory? True if the directory exists, False if it does not
Out[62] :True

In [63]: p.is_dir() Return True if the path points to a directory (or a symbolic link to a directory), False if it points to another type of file. Whether this path is a directory.
Out[63] :True
Copy the code

支那

Pure path

** Path-only objects provide path-handling operations that do not actually access the file system. PurePath(* Pathsegments) A generic class that represents the path style of the current system (instantiated as PurePosixPath or PureWindowsPath) :

In [74] :from pathlib import PurePath

In [75]: PurePath('setup.py')      # Running on a Unix machine
Out[75]: PurePosixPath('setup.py')
Copy the code

Each element of pathsegments may be a string that represents a pathsegment, an object that implements the OS. PathLike interface that returns a string, or another path object:

In [76]: PurePath('foo'.'some/path'.'bar')
Out[76]: PurePosixPath('foo/some/path/bar')

In [77]: PurePath(Path('foo'), Path('bar'))
Out[77]: PurePosixPath('foo/bar')
Copy the code

When pathsegments is empty, assume the current directory:

In [86]: PurePath()
Out[86]: PurePosixPath('. ')
Copy the code

When given some absolute paths, the last one is used as an anchor (mimicking the behavior of os.path.join()) :

In [90] :from pathlib import PurePath, PureWindowsPath

In [91]: PurePath('/etc'.'/usr'.'lib64')
Out[91]: PurePosixPath('/usr/lib64')

In [92]: PureWindowsPath('c:/Windows'.'/Program Files')
Out[92]: PureWindowsPath('c:/Program Files')
Copy the code

False slashes and individual dots are eliminated, but double dots (‘.. ‘) no, in case you change the meaning of symbolic links.

In [93]: PurePath('foo//bar')
Out[93]: PurePosixPath('foo/bar')

In [94]: PurePath('foo/./bar')
Out[94]: PurePosixPath('foo/bar')

In [95]: PurePath('foo/.. /bar')
Out[95]: PurePosixPath('foo/.. /bar')
Copy the code

PurePosixPath(‘foo/.. /bar’) is the same as PurePosixPath(‘bar’), which would be wrong if foo was a symbolic link to another directory.) Pure path objects implement the OS.pathlike interface, allowing them to be used wherever this interface is accepted. Changed in version 3.6: _ Added OS.PathLike interface support. Class pathlib.PurePosixPath(*pathsegments) A subclass of PurePath with a path style different from that of the Windows file system:

In [98]: PurePosixPath('/etc')
Out[98]: PurePosixPath('/etc')
Copy the code

The pathsegments parameter is specified in the same way as PurePath. Class pathlib. ‘ ‘PureWindowsPath(*pathsegments) A subclass of PurePath with paths styled as Windows file system paths:

In [100]: PureWindowsPath('c:/Program Files/')
Out[100]: PureWindowsPath('c:/Program Files')
Copy the code

The pathsegments parameter is specified in the same way as PurePath. You can instantiate these classes no matter what system you are running, because the operations they provide do not make any system calls.

General properties

Paths are immutable and hashable. Paths of the same style can be sorted and compared. These properties respect the case conversion semantics of the corresponding style:

In [101]: PurePosixPath('foo') == PurePosixPath('FOO')
Out[101] :False

In [102]: PureWindowsPath('foo') == PureWindowsPath('FOO')
Out[102] :True

In [103]: PureWindowsPath('FOO') in { PureWindowsPath('foo') }
Out[103] :True

In [104]: PureWindowsPath('C:') < PureWindowsPath('d:')
Out[104] :True
Copy the code

Path comparisons of different styles yield unequal results and cannot be sorted:

In [105]: PureWindowsPath('foo') == PurePosixPath('foo')
Out[105] :False
Copy the code

For more information: docs.python.org/zh-cn/3/lib…