準備開一個長期專題晒他,將學習《Python標準庫》中的一些demo記錄下來吱型,方便查詢和回憶。Python的版本是3.7陨仅,官網文檔在https://docs.python.org/zh-cn/3.7/library/index.html
Pathlib是Python 3.4新加入的一個操作路徑相關函數的模塊津滞,用于替代os.path模塊。Pathlib提供Path類去處理灼伤,而不是直接操作字符串触徐。
Pathlib主要有PurePath類和繼承而來的子類Path,前者是沒有IO的純路徑狐赡,后者是可以有IO操作的具體路徑撞鹉。一般情況下直接使用Path即可。
羅列一些常用的方法和熟悉:
from pathlib import PurePath
p = PurePath()
p2 = p / 'app' / 'core' # 拼接路徑的方法一
print(p2.joinpath("work1.py")) # 拼接路徑的方法二, 返回PurePath對象
print(p2.parent) # 返回父路徑鸟雏,Path對象
print(p2.name) # 返回最后路徑組件的字符串享郊,string
print(p2.suffix) # 返回最后一個組件的文件擴展名,如果有的話孝鹊,string
print(p2.stem) # 返回最后一個路徑組件炊琉,除去后綴,string
print(p2.match("/*.py")) # 模塊匹配
Path類除了上述方法外又活,還有一些其他的:
from pathlib import Path
p = Path()
print(p.cwd()) # 當前目錄的路徑對象
print(p.home()) # 當前用戶家目錄
print(p.resolve()) # 絕對路徑
print(p.joinpath("work1.py").exists()) # 是否存在
print(list(p.glob('*/*.py'))) # 解析相對于此路徑的通配符 pattern苔咪,產生所有匹配的文件
print(p.is_file())
print(p.is_dir())
[print(x) for x in p.iterdir() if x.is_dir()] # 產生該路徑下的對象的路徑
p4 = p / "abc"
p4.mkdir(exist_ok=True) # 創(chuàng)建文件夾
p4.rmdir() # 刪除文件夾
p6 = p / 'test.txt'
p6.touch() # 創(chuàng)建文件
data = ['hello world', 'bye']
with p6.open("a") as f: # 寫文件
for d in data:
f.write(d+'\n')
with p6.open() as f: # 讀文件
for line in f.readlines():
print(line.strip())
p6.rename(Path('test1.txt')) # 重命名方法一
p7 = p / 'test1.txt'
p7.replace(Path('test2.txt')) # 重命名方法二
p8 = p / 'test2.txt'
p8.unlink() # 刪除文件
最后是pathlib和os.path方法的映射表,熟悉那個用那個吧柳骄。
1620376634671.jpg