Home > Article > Backend Development > How to use the Python file system module pathlib library
pathlib is a built-in library of Python. The definition given by the Python documentation is Object-oriented filesystem paths. pathlib provides classes representing file system paths, with semantics applicable to different operating systems.
The path classes are divided between pure paths, which provide pure computational operations without I/O, and concrete paths, which inherit pure paths but also provide I/O operations.
Path.iterdir() # Traverse the subdirectories of the directory or File
Path.is_dir() # Determine whether it is a directory
glob () # Filter directory (return to generator)
() # Return absolute path
() # Determine whether the path exists
() # Open the file (supports with)
() # Delete a file or directory (the directory is not empty and triggers an exception)
# Splitting the path is similar to os.path.split(), but returns a tuple
# Returns the drive name
# Returns the root directory of the path
# Automatically determine and return drive or root
# Return a list of all parent directories
() # Change the path name, change the last level path name
() # Change path suffix
() #Join path
() #Calculate relative path
##5 , Test pathPath.
##Path.
is_absolutePath .
is_reservedPath.
exists6. Other methods
Path.
homePath.
statPath.
chmodPath.
expanduserPath.
mkdirPath.
renamePath.
rglob3. The difference between os and pathlib.Path
When using the os module, you can directly get the current file path through the
getcwd()In Pycharm, You can use os.path.dirname(__file__)
to get the current file path, because Python does not provide the concept of __file__, which is provided by Pycharm:
import os print(os.getcwd()) # C:\Users\bobin.yang\PycharmProjects\untitled print(os.path.dirname(__file__)) # C:/Users/bobin.yang/PycharmProjects/untitled
In the pathlib module, pass Path.cwd()
method can directly obtain the current file path, we can give it a try:
import pathlib print(pathlib.Path.cwd()) # C:\Users\bobin.yang\PycharmProjects\untitled
Through Pycharm we can use shortcut keys ctrl left mouse button
Click to view a detailed introduction to this method.
As can be seen from the above picture, the cwd()
method is just an encapsulation of the
method in the os library. It looks even worse. But the official launch is definitely not a fiction. Now let us reveal the secret together. 2. Get the upper/upper directory
The above case seems to make the use of the pashlib library more complicated. In order to reveal the secret, we can only feel the composition of the pathlib library and understand pathlib How libraries bring us convenience.
import os print(os.path.dirname(os.path.dirname(os.getcwd()))) # C:\PycharmProjects
In the pathlib library, it can be achieved in this simple way:
import pathlib print(pathlib.Path.cwd().parent) # C:\PycharmProjects
And if you need to find his grandfather, just ask for another
.parent. Compared with the os module's
os.path.dirname(), is it too convenient? 3. Path splicing
If you want to splice the path in its parent directory, you may need to write such a long string of code through the os module:
import os print(os.path.join(os.path.dirname(os.getcwd()), '路径拼接', '真麻烦')) # C:\PycharmProjects\路径拼接\真麻烦
# /Users/mac/test.py import os paths = ('路径拼接', '真麻烦') print(pathlib.Path.cwd().parent.joinpath(*paths)) # C:\PycharmProjects\路径拼接\真麻烦
通过 pathlib 库拼接路径,你可以很方便的调节他在他祖辈的位置,妙哉。
pathlib 封装了很多的 os.path 中的方法,如下所示:
os.path.expanduser() --> pathlib.Path.home()
os.path.expanduser() --> pathlib.Path.expanduser()
os.stat() --> pathlib.Path.stat()
os.chmod() --> pathlib.Path.chmod()
上一节的操作大部分都是通过 pathlib 库中的 Path 实现,其实他还有一个更加高大上的模块,也就是我们这一节的主角:pathlib.PurePath
。
PurePath 是一个纯路径对象,纯路径对象提供了实际上不访问文件系统的路径处理操作。
有三种方法可以访问这些类,我们也称之为 flavor 。
下面让我们来实现一个神奇的功能,判断当前的路径下是否有符合'*.py'规则的文件。
import pathlib print(pathlib.PurePath(__file__).match('*.py')) # True
输出为什么会是 True
呢?因为当前文件夹下不就有一个 test.py
吗?
看见 pathlib.PurePath 后面跟着 match,那是不是能说明他是个对象,而不是一个单纯的路径字符串,因此我们可以试着打印 pathlib.PurePath 看一看。
import pathlib os_path = os.path.dirname(__file__) print(os_path) # C:/PycharmProjects/untitled pure_path = pathlib.PurePath(__file__) print(pure_path) # C:\PycharmProjects\untitled\run.py print(type(pure_path)) # <class 'pathlib.PureWindowsPath'> print(pathlib.PurePath(__file__).match('*.py')) # True
通过打印 os.path 获取当前路径的结果,得到一个路径字符串;而通过 pathlib.PurePath 则获得了一个 PurePosixPath 对象,并且由此得到的路径包括了当前文件 run.py。
The above is the detailed content of How to use the Python file system module pathlib library. For more information, please follow other related articles on the PHP Chinese website!