8. Use library for files and directories
This library primarily provides the ability to handle disk file and directory related functions. For example, some modules read file attributes, or use a common way to manipulate file paths, or create a temporary file.
8.1 pathlib--file system path for object-oriented design
This module mainly provides the operation mode of the file system path under different operating systems. The path class is divided into pure path operations with no I/O operations and classes with I/O operations related. The inheritance diagram for the entire path is as follows:
If you have never used the classes in this module and are not sure what class to use, you can use the path class first, which provides some classes to assist in manipulating the path.
Pure path operation in some cases, there are special needs:
1. For example, operating Windows path under Unix system , there is no way to use Windowspath under Unix class, you can use the purewindowspath class.
2. For example, only want to operate the path, but do not access the OS path-related features.
8.1.1Basic Use
Import the primary used class and display the current subdirectory:
#python 3.4
From Pathlib import Path
p = Path ('. ')
R = [x for x in P.iterdir () if X.is_dir ()]
Print (R)
The resulting output is as follows:
[Windowspath (' Micropython-master ')]
Find files in a directory, determine if the path is a directory, determine if the file exists
Example:
#python 3.4
From Pathlib import Path
p = Path (' f:\\temp\\py ')
Print (List (P.glob (' **/*.py ')))
Q = P/' cal_1.py '
Print (q, Q.resolve (), q.exists (), Q.is_dir ())
The resulting output is as follows:
[Windowspath (' f:/temp/py/bisect1.py '), Windowspath (' f:/temp/py/cal_1.py '), Windowspath (' f:/temp/py/chainmap1.py ') ), Windowspath (' f:/temp/py/chainmap2.py '), Windowspath (' f:/temp/py/closescreen.py '), Windowspath (' F:/temp/py/ codecs1.py '), Windowspath (' f:/temp/py/complex1.py '), Windowspath (' f:/temp/py/copy1.py '), Windowspath (' F:/temp/py/ datetimetz.py '), Windowspath (' f:/temp/py/dec1.py '), Windowspath (' f:/temp/py/difflib1.py '), WindowsPath (' F:/temp/ py/difflib2.py '), Windowspath (' f:/temp/py/difflib3.py '), Windowspath (' f:/temp/py/difflib4.py '), WindowsPath (' F:/ temp/py/difflib5.py ')]
F:\temp\py\cal_1.py F:\temp\py\cal_1.py True False
Cai Junsheng qq:9073204 Shenzhen
8.1 pathlib--File system path for object-oriented design