pathlib Library in python 3.4 It has become a standard library , It can basically replace os.path
To deal with paths . It uses a completely object-oriented programming approach .
All in all 6 Classes are used to handle paths , It can be roughly divided into two categories :
this 6 The inheritance relationship of classes is as follows :
You can see PurePath
Is the base class of all classes , We should grasp the key point of PurePath
and Path
These two classes , stay Windows Path objects under the platform will have Windows Prefix ,Unix Path objects on the platform will have Posix Prefix .
List all subdirectories
import pathlib
p = pathlib.Path('.')
[x for x in p.iterdir() if x.is_dir()]
# result
[WindowsPath('.git'), WindowsPath('.idea'), WindowsPath('.vscode'),
WindowsPath('1_ Function parameter '), WindowsPath('2_ generator '), WindowsPath('3_ Common functions '),
WindowsPath('4_ Decorator ), WindowsPath('5_ Common modules ')]
# stay linux In the environment , Aforementioned WindowsPath Will become PosixPath
List files of the specified type
list(p.glob('**/*.py'))
Path splicing
have access to /
Symbols to splice paths
p = pathlib.Path(r'F:\cookies\python')
q = p / 'learnPython'
print(q)
# result
F:\cookies\python\learnPython
Query attribute
q.exists()
# result
True
q.is_dir()
# result
True
Open file
q = q / "hello_world.py"
with q.open() as f:
print(f.readline())
# result
#!/usr/bin/env python
Path Calculation
PurePosixPath('foo') == PurePosixPath('FOO')
# result
False
PureWindowsPath('foo') == PureWindowsPath('FOO')
# result
True
PureWindowsPath('FOO') in { PureWindowsPath('foo') }
# result
True
PureWindowsPath('C:') < PureWindowsPath('d:')
# result
True
PureWindowsPath('foo') == PurePosixPath('foo')
# result
False
PureWindowsPath('foo') < PurePosixPath('foo')
# result
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: PureWindowsPath() < PurePosixPath()
str() and bytes()
p = PurePath('/etc')
str(p)
# result
'/etc'
p = PureWindowsPath('c:/Program Files')
str(p)
# result
'c:\\Program Files'
bytes(p)
# result
b'/etc'
from pathlib import Path
file = "D:/99-Research/Python/Image"
p = Path(file)
p.cwd() # Get the current path
p.stat() # Get information about the current file
p.exists() # Determine whether the current path is a file or folder
p.glob(filename) # Get all matches in the path filename The file of , Return to one generator
p.rglob(filename) # Similar to the above , It's just a match for all subfolders in the return path filename The file of
p.is_dir() # Determine whether the path is a folder
p.is_file() # Determine whether the path is a file
p.iterdir() # When path When it's a folder , adopt yield produce path All the files under the folder 、 Iterator of folder path
P.mkdir(parents=Fasle) # Create a folder based on the path ,parents=True when , The missing folder in the middle of the path will be created in turn
p_news = p/'new_dirs/new_dir'
p_news.mkdir(parents=True)
P.open(mode=’r’, buffering=-1, encoding=None, errors=None, newline=None) # Be similar to open() function
p.rename(target) # When target yes string when , Rename a file or folder ; When target yes Path when , Rename and move files or folders
p.replace(target) # Rename the current file or folder , If target The indicated file or folder already exists , Then overwrite the original file
p.parent(),p.parents() # parent obtain path The superior path of ,parents obtain path All the superior paths of
p.is_absolute() # Judge path Is it an absolute path
p.match(pattern) # Judge path Is it satisfactory? pattern
p.rmdir() # When path When the folder is empty , Delete this folder
p.name # obtain path file name
p.suffix # obtain path file extension