Study Python when , Especially in file operation and data processing , Often deal with path problems . The most commonly used and common is os.path modular , It treats the path as a string , Improper use may lead to imperceptible errors , And the code is difficult to reuse across platforms .pathlib
It's a great Python Standard library , Super easy to use .
pathlib
The module provides a way to POSIX System ( Such as Linux and Windows) High level abstraction that works well under , It abstracts the resource path and resource naming structure , File system interface from os Isolated from the module , Use actions as Method
Provide , It's easier to use .
Here's a picture , Perfect interpretation pathlib
At the heart of
pathlib Basic components
>>> from pathlib import Path
>>> path = Path(r'C:/Users/Miguel/projects/blog/config.tar.gz')
>>> path.drive
'C:'
>>> path.root
'/'
>>> path.root
'C:/'
>>> path.parent
WindowsPath('C:/Users/Miguel/projects/blog')
>>> path.name
'config.tar.gz'
>>> path.stem
'config.tar'
>>> path.suffix
'.gz'
>>> path.suffixes
['.tar', '.gz']
pathlib
Common properties of
Path.parents # Return a list of all parent directories
Path.parts # Split the path similar os.path.split(), But return tuples
Path.suffix # Return file suffix
pathlib
Common basic methods of
Path.is_dir() # Determine if it's a directory
Path.is_file() # Is it a document
Path.exists() # Determine if the path exists
Path.open() # Open file ( Support with)
Path.resolve() # Return to absolute path
Path.cwd() # Return to the current directory
Path.iterdir() # Traverse the subdirectories or files of the directory
Path.mkdir() # Create directory
Path.rename() # Rename path
Path.unlink() # Delete files or directories ( Directory non empty trigger exception )
Path.joinpath() # Splicing path
pathlib
Substitutable os and os.path Common functions of :
pathlib
Create a path as an object , It provides a convenient and fast method to deal with file paths .
I don't list in this article pathlib
Every use of , I think the most important thing is to Full understanding pathlib Basic components , Then check the document if you have any questions .
Reference resources :
https://miguendes.me/python-pathlib https://docs.python.org/3/library/pathlib.html
https://www.cnblogs.com/poloyy/p/12435628.html
Welcome to reprint 、 Collection 、 Gain some praise and support !
At present, a technical exchange group has been opened , Group friends have exceeded 2000 people , The best way to add notes is : source + Interest direction , Easy to find like-minded friends