pathlib - more elegant handling of path problems

In general, because pathon3's standard library adds a new member, pathlib, path calls can be much more elegant. And python2 is terrible by comparison.

For example this piece of code:

import os
import sys
curpath=os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'a_diretory')
sys.path.append(curpath)

It's enough to highlight the badness of pathon2. For the above function, python3 can write like this

import sys
from pathlib import Path
sys.path.append(Path().parent.parent.joinpath('a_diretory'))

I don't want to describe too much here, just put a piece of test code below . The test code involves the processing of the path and the import of the package.

# Pyhon 3 新方式
from pathlib import Path

print('Python 3:')
p = Path(r'C:\Users\Admin\Desktop\pythonTest')  # 创建了一个路径对象
print(p)

# Python 2 典型的方式
import os

print('\nPython 2: Unix-Style')
path1 = os.path.dirname(__file__)
print(path1)  # 获取当前运行脚本的文件目录
path2 = os.path.dirname(os.path.dirname(__file__))  
print(path2)  # 获取当前运行脚本的文件目录(去掉最后一个路径)
path3 = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
print(path3)  # 获取当前运行脚本的绝对路径(去掉最后2个路径)
path4 = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
print(path4)  # 获取当前运行脚本的绝对路径(去掉最后3个路径),省略...

print('\nPython 2: OS-Style')
path1 = os.path.abspath(__file__)
print(path1)  # 获取当前运行脚本的绝对路径
path2 = os.path.dirname(path1)
print(path2)
path3 = os.path.dirname(path2)
print(path3)
path4 = os.path.dirname(path3)
print(path4)

# 获取python编译器的所在的目录  OS -style
pyInterpreterPath = os.__file__
print('\nPython Interpreter Path:')
print(pyInterpreterPath,'\n')

# 包的导入--python2
# 这里假设导入一个兄弟节点的包,该包的名字是: A_Package_Dir,我在里面放了一个脚本叫hahaha,定义了add加法函数。
import sys
import os
apiPath = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'A_Package_Dir')
sys.path.append(apiPath)
print('Python2:', apiPath)
import hahaha
hahaha.add(1,2)
sys.path.remove(apiPath)

# 包的导入--python3
apiPath = Path().absolute().parent.joinpath('A_Package_Dir')
print('Python3:', apiPath)
sys.path.append(str(apiPath))
import hahaha
hahaha.add(1,2)

Result of running:

C:\Python36\python.exe C:/Users/Admin/Desktop/pythonTest/studyPathlib.py
Python 3:
C:\Users\Admin\Desktop\pythonTest

Python 2: Unix-Style
C:/Users/Admin/Desktop/pythonTest
C:/Users/Admin/Desktop
C:/Users/Admin
C:/Users

Python 2: OS-Style
C:\Users\Admin\Desktop\pythonTest\studyPathlib.py
C:\Users\Admin\Desktop\pythonTest
C:\Users\Admin\Desktop
C:\Users\Admin

Python Interpreter Path:
C:Python36\lib\os.py 

Python2: C:\Users\Admin\Desktop\A_Package_Dir
3
Python3: C:\Users\Admin\Desktop\A_Package_Dir
3

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325212436&siteId=291194637