目錄操作
導入主要的類
from pathlib import Path
初始化
>>> p = Path() # 當前目錄 >>> p = Path('a','b','c/d') # 當前目錄下的a/b/c/d >>> p = Path('/etc') # 根下的etc目錄
路徑拼接和分解
拼接操作符:/
Path對象 / Path對象
Path對象 / 字符串
字符串 / Path對象
分解
parts屬性,可以返回路徑中的每一部分
joinpath
joinpath(*other)連接多個字符串到Path對象中
>>> p = Path() >>> p WindowsPath('.') >>> p = p / 'a' >>> p WindowsPath('a') >>> p1 = 'b' / p >>> p1 WindowsPath('b/a') >>> p2 = Path('c') >>> p3 = p2 / p1 >>> p3 WindowsPath('c/b/a') >>> p3.parts ('c', 'b', 'a') >>> p3.joinpath('C:', 'Users', 'Administrator', 'Desktop') WindowsPath('C:Users/Administrator/Desktop')
獲取路徑
獲取路徑字符串
獲取路徑字符串的bytes
>>> p = Path('C:/Users/Administrator/Desktop/') >>> print(str(p), bytes(p)) C:\Users\Administrator\Desktop b'C:\\Users\\Administrator\\Desktop'
父目錄
parent屬性 目錄的邏輯父目錄
parents屬性 父目錄序列,索引0是直接的父目錄,索引越大越接近根
>>> p = Path('C:/Users/Administrator/Desktop/') >>> p.parent WindowsPath('C:/Users/Administrator') >>> p.parent.parent WindowsPath('C:/Users') >>> for x in p.parents: print(x) C:\Users\Administrator C:\Users C:\
文件名
name 目錄的最后一個部分
suffix 目錄中最后一個部分的擴展名
suffixes 返回多個擴展名列表
stem 目錄最后一個部分,沒有后綴
with_name(name) 替換目錄最后一個部分並返回一個新的路徑
with_suffix(suffix) 替換擴展名,返回新的路徑,擴展名存在則不變
>>> p = Path('/hidog/text.tar.gz') >>> p.name 'text.tar.gz' >>> p.suffix '.gz' >>> p.suffixes ['.tar', '.gz'] >>> p.stem 'text.tar' >>> p.with_name('haha.tgz') WindowsPath('/hidog/haha.tgz') >>> p.with_suffix('.gz') WindowsPath('/hidog/text.tar.gz') >>> p.with_suffix('.txt') WindowsPath('/hidog/text.tar.txt')
cwd()
返回一個表示當前目錄的新路徑對象:
>>> Path.cwd() WindowsPath('C:/Users/Administrator/my_practice') >>> p = Path() >>> p.cwd() WindowsPath('C:/Users/Administrator/my_practice')
home()
返回一個表示當前用戶HOME目錄的新路徑對象:
>>> Path.home() WindowsPath('C:/Users/Administrator')
判斷路徑的類型
返回:布爾值
is_dir() 是否是目錄
is_file() 是否是普通文件
is_symlink() 是否是軟鏈接
is_socket() 是否是socket文件
is_block_device() 是否是塊設備
is_char_device() 是否是字符設備
is_absolute() 是否是絕對路徑
resolve() 返回一個新的路徑,這個新路徑就是當前Path對象的絕對路徑,如果是軟鏈接則直接被解析
absolute() 也可以獲取絕對路徑,但是推薦resolve()
exists()
該路徑是否指向現有的目錄或文件:
>>> Path('C:/Users/Administrator/Desktop/text.txt').exists() True
rmdir() 刪除空目錄。沒有提供判斷目錄是否為空的方法
touch(mode=0o666, exist_ok=True) 創建一個文件
as_uri() 將路徑返回成URI(Uniform Resource Identifier,統一資源標識符,是一個用於標識某一互聯網資源名稱的字符串),例如'file:///etc/passwd'
mkdir(mode=0o777,parents=False,exist_ok=False) 創建目錄
parents:是否創建父目錄,True等同mkdir -p;False時,父目錄不存在,則拋出FileNotFoundError
exist_ok:在3.5版本加入。False時,路徑存在,拋出FileExistsError;True時,FileExistsError被忽略
>>> p = Path('C:/Users/Administrator/Desktop/') >>> p = p / 'test' / 'test1' >>> p.mkdir(parents=True) # 在桌面上創建test目錄,創建test1目錄
iterdir() 迭代當前目錄:
>>> p = Path('C:/Users/Administrator/Desktop/') >>> [x for x in p.iterdir()] [WindowsPath('C:/Users/Administrator/Desktop/reg.txt'), WindowsPath('C:/Users/Administrator/Desktop/新建文件夾'), WindowsPath('C:/Users/Administrator/Desktop/Path.pdf'), …… WindowsPath('C:/Users/Administrator/Desktop/Xshell.lnk')]
通配符
glob(pattern) 通配給定的模式
rglob(pattern) 通配給定的模式,遞歸目錄
返回一個生成器
>>> p = Path('C:/Users/Administrator/Desktop/') >>> list(p.glob('test*')) # 返回當前目錄對象下的以test開頭的文件 [WindowsPath('C:/Users/Administrator/Desktop/test.ini'), WindowsPath('C:/Users/Administrator/Desktop/test.py')] >>> list(p.glob('**/*.txt')) # 遞歸所有目錄,返回txt格式的文件,等同rglob [WindowsPath('C:/Users/Administrator/Desktop/reg.txt'), WindowsPath('C:/Users/Administrator/Desktop/sample.txt'), WindowsPath('C:/Users/Administrator/Desktop/text.txt'), WindowsPath('C:/Users/Administrator/Desktop/newfolder/新建文本文檔.txt'), WindowsPath('C:/Users/Administrator/Desktop/newfolder/newfolder1/新建文本文檔1.txt')] >>> g = p.rglob('*.py') # 生成器 >>> next(g) WindowsPath('C:/Users/Administrator/Desktop/test.py')
匹配
match(pattern)
模式匹配,成功返回True
>>> p = Path('C:/Users/Administrator/Desktop/text.txt') >>> p.match('*.txt') True >>> Path('C:/Users/Administrator/Desktop/text.txt').match('**/*.txt') True
stat() 相當於stat命令
lstat() 同stat(),但如果是符號鏈接(軟鏈接),則顯示符號鏈接本身的文件信息
返回路徑的信息,每次調用此方法時都要查看結果:
>>> p = Path('C:/Users/Administrator/Desktop/text.txt') >>> p.stat() os.stat_result(st_mode=33206, st_ino=2533274790402060, st_dev=48152560, st_nlink=1, st_uid=0, st_gid=0, st_size=12, st_atime=1524986835, st_mtime=1525066548, st_ctime=1524986835) >>> p.stat().st_size # 文件大小12字節 12 >>> p.lstat() os.stat_result(st_mode=33206, st_ino=2533274790402060, st_dev=48152560, st_nlink=1, st_uid=0, st_gid=0, st_size=12, st_atime=1524986835, st_mtime=1525066548, st_ctime=1524986835)
文件操作
open(mode='r', bufferiong=-1, encoding=None, errors=None, newline=None)
使用方法類似內建函數open。返回一個文件對象
>>> p = Path('C:/Users/Administrator/Desktop/text.txt') >>> with p.open(encoding='utf-8') as f: print(f.readline()) # win下‘GBK’,需要轉碼 測試一下
read_bytes()
以'rb'讀取路徑對應文件,並返回二進制流
Path.write_bytes(data)
以'wb'方式寫入數據到路徑對應文件
>>> p = Path('C:/Users/Administrator/Desktop/text.txt') >>> p.write_bytes(b'Binary file contents') 20 >>> p.read_bytes() b'Binary file contents'
read_text(encoding=None, errors=None)
以'rt'方式讀取路徑對應文件,返回文本
write_text(data, encoding=None, errors=None)
以'wt'方式寫入字符串到路徑對應文件
>>> p = Path('C:/Users/Administrator/Desktop/text.txt') >>> p.write_text('Text file contents') 18 >>> p.read_text() 'Text file contents'