This article is participating in Python Theme Month. See the link for details

I believe you must use OS library for file system operations, such as file read and write, path combination, upload and download will involve the file path. However, it is not elegant to use OS libraries for certain operations, such as finding superior paths, handling paths between different operating systems, etc. Today we introduce Python’s built-in object-oriented path library, Pathlib.

1. Obtain the current file path

from os import path
exec_path = path.dirname(__file__)
print(exec_path,type(exec_path))
 
from pathlib import Path,PurePath
cur_path = Path(__file__).parent
print(cur_path,type(cur_path))
Copy the code

Running results:

e:/TestProject/iaas/test_data <class 'str'>
e:\TestProject\iaas\test_data <class 'pathlib.WindowsPath'>
Copy the code

summary

  1. The path returned by the OS library is the STR object

  2. The path pathlib returns is a WindowsPath object

  3. WindowsPath objects have many path attributes, whereas STR has only STR attributes

2. Get the name of the current file

from os import path
exec_path = path.basename(__file__)
print(exec_path,type(exec_path)) 
 
from pathlib import Path,PurePath
cur_path = Path(__file__).name
print(cur_path,type(cur_path))
Copy the code

Running results:

t_test.py <class 'str'>
t_test.py <class 'str'>
Copy the code

summary

  1. The basename method is used to obtain the current file name in the OS library

  2. Pathlib gets the current file name just by getting the value of the name attribute

3. Find the parent path

from os import path,getcwd
Cur_path: current path par_path: parent path gra_path: parent path
cur_path = path.dirname(__file__)
par_path = path.dirname(path.dirname(__file__))
gra_path = path.dirname(path.dirname(path.dirname(__file__)))
print(cur_path)
print(par_path)
print(gra_path)
 
from pathlib import Path,PurePath
cur_path = Path(__file__).parent
par_path = cur_path.parent
gra_path = par_path.parent
print(cur_path)
print(par_path)
print(gra_path)
Copy the code

Running results:

e:/TestProject/iaas/test_data
e:/TestProject/iaas
e:/TestProject
e:\TestProject\iaas\test_data
e:\TestProject\iaas
e:\TestProject
Copy the code

summary

The Pathlib approach is much more elegant than the OS approach and highlights the advantages of object orientation.

4, Pathlib PurePath and Path

  1. PurePath stands for PurePath, does not represent real path and file, PurePath object operation

  2. Path represents the real Path and file. You can determine whether the Path or file’s properties and existence exist

  3. Path is a subclass of PurePath and supports PurePath properties and methods

  4. PurePath has two subclasses, PureWindowsPath and PurePosixPath, which represent PurePath objects for different operating systems

Windows:

from pathlib import Path,PurePath
cur_path = Path(__file__)
print(cur_path,type(cur_path))
 
 
pur_path = PurePath(__file__)
print(pur_path,type(pur_path))
Copy the code

Running results:

e:\TestProject\iaas\test_data\t_test.py <class 'pathlib.WindowsPath'>
e:\TestProject\iaas\test_data\t_test.py <class 'pathlib.PureWindowsPath'>
Copy the code

Linux:

>>> from pathlib import PurePath
>>> from pathlib import Path
>>> cur_path = Path('/home/env/internet')
>>> print(cur_path,type(cur_path))
/home/env/internet <class 'pathlib.PosixPath'> > > >pur_path = PurePath('/home/env/internet') > > >print(pur_path,type(pur_path))
/home/env/internet <class 'pathlib.PurePosixPath'>
Copy the code

summary

Using PurePath allows unified operation of paths across operating systems.

5, Pathlib and OS function comparison

6, common pathlib.Path related methods

Path.iterdir()Walk through subdirectories or files of a directoryPath.is_dir()Check if it is a directoryPath.glob()# filter directory (return generator)Path.resolve()Return absolute pathPath.exists()Check whether the path exists
 
 
Path.open(a)# Open file (with support)Path.unlink()# delete file or directory (directory is not empty)Path.partsThe split path is similar to os.path.split(), but returns a tuplePath.drive# Return the drive namePath.rootReturn the root of the pathPath.anchorReturn drive or rootPath.parentsReturn a list of all parent directoriesPath.with_name()Change the last level pathnamePath.with_suffix()Change the path suffixPath.joinpath()# splice pathPath.relative_to()# Calculate the relative pathPath.match()# test whether the path matches patternPath.is_dir()Is it a file?Path.is_absolute()Is it an absolute pathPath.is_reserved()# Check whether the path is reservedPath.exists()Check whether the path really existsPath.cwd()Return the path object of the current directoryPath.home()Return the current user's home path objectPath.stat()# return path information, same as os.stat()Path.chmod()# Change path permissions, similar to os.chmod()Path.expanduser()Return the full path objectPath.mkdir()Create a directoryPath.rename()Rename the pathPath.rglob()Recursively traverses files in all subdirectories
Copy the code