Python pathlib模塊使用實(shí)例教程
pathlib 是 Python 3.4+ 引入的面向?qū)ο蟮奈募窂教幚砟K,比 os.path 更現(xiàn)代、更直觀。它提供了 Path 類來表示文件系統(tǒng)路徑。
1. 基本導(dǎo)入和初始化
from pathlib import Path
# 創(chuàng)建路徑對(duì)象
p1 = Path() # 當(dāng)前目錄
print(p1) # .
p2 = Path('documents') # 相對(duì)路徑
print(p2) # documents
p3 = Path('/home/user/file.txt') # 絕對(duì)路徑
print(p3) # /home/user/file.txt
# 支持多級(jí)路徑拼接(不需要 join)
p4 = Path('home') / 'user' / 'docs' / 'readme.md'
print(p4) # home/user/docs/readme.md2. 路徑拼接與拆分
2.1 使用/運(yùn)算符拼接
# 使用斜杠拼接(跨平臺(tái))
root = Path('/home/user')
full_path = root / 'documents' / 'notes.txt'
print(full_path) # /home/user/documents/notes.txt
# 也可以使用 joinpath()
path = Path('/tmp')
full = path.joinpath('data', 'logs', 'app.log')
print(full) # /tmp/data/logs/app.log
# 支持字符串和Path對(duì)象混用
base = Path('/var')
new = base / 'www' / 'html'
print(new) # /var/www/html2.2 獲取路徑各部分
path = Path('/home/user/documents/file.tar.gz')
# 獲取文件名(包含所有擴(kuò)展名)
print(path.name) # file.tar.gz
# 獲取不帶擴(kuò)展名的文件名
print(path.stem) # file.tar
# 獲取擴(kuò)展名(最后一個(gè)點(diǎn)之后)
print(path.suffix) # .gz
# 獲取所有擴(kuò)展名(Python 3.12+)
print(path.suffixes) # ['.tar', '.gz']
# 獲取父目錄
print(path.parent) # /home/user/documents
print(path.parent.parent) # /home/user
# 獲取所有祖先
for parent in path.parents:
print(parent)
# /home/user/documents
# /home/user
# /home
# /
# 獲取根目錄
print(path.anchor) # /2.3 拆分組裝示例
# 實(shí)際應(yīng)用:替換文件擴(kuò)展名
file = Path('report.xlsx')
new_file = file.with_suffix('.pdf')
print(new_file) # report.pdf
# 修改文件名
old = Path('data/old_name.txt')
new = old.with_name('new_name.txt')
print(new) # data/new_name.txt
# 組合使用
config = Path('/etc/nginx/nginx.conf')
backup = config.with_name(config.stem + '.backup' + config.suffix)
print(backup) # /etc/nginx/nginx.backup.conf3. 路徑檢查與屬性
# 假設(shè)當(dāng)前目錄有 test.txt 文件和 mydir 目錄
path_file = Path('test.txt')
path_dir = Path('mydir')
path_link = Path('symlink') # 假設(shè)存在符號(hào)鏈接
# 存在性檢查
print(path_file.exists()) # True
print(Path('nonexist').exists()) # False
# 類型檢查
print(path_file.is_file()) # True
print(path_dir.is_file()) # False
print(path_file.is_dir()) # False
print(path_dir.is_dir()) # True
# 其他檢查
print(path_file.is_absolute()) # False
print(Path('/home/file.txt').is_absolute()) # True
print(path_file.is_symlink()) # False
print(path_link.is_symlink()) # True
# 路徑比較(自動(dòng)跨平臺(tái))
p1 = Path('/home/user')
p2 = Path('/home') / 'user'
print(p1 == p2) # True4. 目錄操作
4.1 創(chuàng)建和刪除目錄
# 創(chuàng)建單級(jí)目錄
new_dir = Path('new_folder')
new_dir.mkdir(exist_ok=True) # exist_ok=True 避免已存在時(shí)報(bào)錯(cuò)
print(new_dir.exists()) # True
# 創(chuàng)建多級(jí)目錄
nested = Path('parent/child/grandchild')
nested.mkdir(parents=True, exist_ok=True)
print(nested.exists()) # True
# 刪除目錄(必須為空)
empty_dir = Path('temp_empty')
empty_dir.mkdir()
empty_dir.rmdir() # 刪除空目錄
# 刪除目錄及內(nèi)容(Python 3.12+)
# import shutil
# shutil.rmtree('parent') # 遞歸刪除4.2 列出目錄內(nèi)容
# 列出所有內(nèi)容
docs = Path('/home/user/documents')
for item in docs.iterdir():
print(item.name)
# 輸出示例:
# report.pdf
# images
# notes.txt
# backup
# 使用 glob 模式匹配
# 查找所有 .txt 文件
for txt_file in docs.glob('*.txt'):
print(txt_file)
# /home/user/documents/notes.txt
# /home/user/documents/readme.txt
# 遞歸查找(** 表示任意子目錄)
for py_file in docs.glob('**/*.py'):
print(py_file)
# /home/user/documents/scripts/main.py
# /home/user/documents/tools/helper.py
# 區(qū)分文件和目錄
for item in docs.iterdir():
if item.is_file():
print(f"文件: {item.name}")
elif item.is_dir():
print(f"目錄: {item.name}")5. 文件操作
5.1 讀寫文件
# 寫文件
file_path = Path('example.txt')
# 方法1:write_text
file_path.write_text('Hello, World!', encoding='utf-8')
print(file_path.read_text(encoding='utf-8')) # Hello, World!
# 方法2:write_bytes(二進(jìn)制)
bin_path = Path('data.bin')
bin_path.write_bytes(b'\x00\x01\x02\x03')
print(bin_path.read_bytes()) # b'\x00\x01\x02\x03'
# 方法3:使用 open() 方法(上下文管理)
with file_path.open('a', encoding='utf-8') as f:
f.write('\nAppended line')
print(file_path.read_text(encoding='utf-8'))
# Hello, World!
# Appended line
# 刪除文件
file_path.unlink(missing_ok=True) # missing_ok=True 不報(bào)錯(cuò)5.2 復(fù)制和移動(dòng)文件
from pathlib import Path
import shutil
# 復(fù)制文件
src = Path('source.txt')
dst = Path('backup/source_copy.txt')
# 創(chuàng)建目標(biāo)目錄(如果需要)
dst.parent.mkdir(parents=True, exist_ok=True)
# 復(fù)制
shutil.copy2(src, dst) # 保留元數(shù)據(jù)
print(dst.exists()) # True
# 移動(dòng)/重命名文件
old = Path('old_name.txt')
new = Path('new_name.txt')
old.rename(new) # 重命名
print(new.exists()) # True
print(old.exists()) # False
# 移動(dòng)文件到其他目錄
src = Path('data.txt')
dst = Path('archive/data.txt')
src.rename(dst)
print(dst.exists()) # True6. 文件屬性和信息
path = Path('test.txt')
# 文件大小(字節(jié))
print(path.stat().st_size) # 1024
# 獲取文件信息
stat = path.stat()
print(f"大小: {stat.st_size} 字節(jié)") # 大小: 1024 字節(jié)
print(f"權(quán)限: {oct(stat.st_mode)}") # 權(quán)限: 0o100644
print(f"最后訪問: {stat.st_atime}") # 最后訪問: 1747556123.45
print(f"最后修改: {stat.st_mtime}") # 最后修改: 1747556100.00
# 使用 datetime 格式化時(shí)間
from datetime import datetime
mtime = datetime.fromtimestamp(stat.st_mtime)
print(f"修改時(shí)間: {mtime}") # 修改時(shí)間: 2026-05-18 10:15:00
# 獲取絕對(duì)路徑
print(path.absolute()) # /home/user/project/test.txt
print(path.resolve()) # 解析符號(hào)鏈接后的絕對(duì)路徑
# 獲取相對(duì)路徑
current = Path.cwd()
abs_path = Path('/home/user/project/test.txt')
rel_path = abs_path.relative_to(current)
print(rel_path) # test.txt7. 實(shí)戰(zhàn)示例
7.1 批量重命名文件
def batch_rename(directory, old_ext, new_ext):
"""批量修改文件擴(kuò)展名"""
dir_path = Path(directory)
for file_path in dir_path.glob(f'*.{old_ext}'):
new_path = file_path.with_suffix(f'.{new_ext}')
file_path.rename(new_path)
print(f"重命名: {file_path.name} -> {new_path.name}")
# 重命名: image.jpg -> image.png
# 重命名: doc.jpg -> doc.png
# 使用示例
# batch_rename('./images', 'jpg', 'png')7.2 遞歸統(tǒng)計(jì)文件類型
from collections import Counter
def count_file_types(directory):
"""遞歸統(tǒng)計(jì)目錄中各類型文件數(shù)量"""
dir_path = Path(directory)
type_counter = Counter()
for file_path in dir_path.rglob('*'):
if file_path.is_file():
suffix = file_path.suffix or '無擴(kuò)展名'
type_counter[suffix] += 1
return type_counter
# 使用示例
stats = count_file_types('/home/user/project')
for ext, count in stats.most_common(5):
print(f"{ext:10} : {count} 個(gè)")
# .py : 42 個(gè)
# .txt : 15 個(gè)
# .md : 8 個(gè)
# .json : 5 個(gè)
# 無擴(kuò)展名 : 3 個(gè)7.3 整理文件到日期目錄
from datetime import datetime
import shutil
def organize_by_date(directory):
"""按文件修改日期整理文件到子目錄"""
base_path = Path(directory)
for file_path in base_path.iterdir():
if not file_path.is_file():
continue
# 獲取修改日期
mtime = datetime.fromtimestamp(file_path.stat().st_mtime)
date_dir = base_path / mtime.strftime('%Y/%m')
# 創(chuàng)建日期目錄
date_dir.mkdir(parents=True, exist_ok=True)
# 移動(dòng)文件
dest = date_dir / file_path.name
shutil.move(str(file_path), str(dest))
print(f"移動(dòng): {file_path.name} -> {dest}")
# 移動(dòng): report.pdf -> ./2026/05/report.pdf
# 使用示例
# organize_by_date('./downloads')7.4 查找和清理空文件夾
def find_empty_dirs(directory):
"""遞歸查找所有空文件夾"""
base_path = Path(directory)
empty_dirs = []
# rglob 查找所有目錄,sort 確保先處理深層目錄
for dir_path in sorted(base_path.rglob('*'), reverse=True):
if dir_path.is_dir():
try:
next(dir_path.iterdir()) # 嘗試獲取第一個(gè)子項(xiàng)
except StopIteration:
empty_dirs.append(dir_path)
return empty_dirs
def clean_empty_dirs(directory, dry_run=True):
"""清理空文件夾"""
empty_dirs = find_empty_dirs(directory)
for dir_path in empty_dirs:
if dry_run:
print(f"[模擬] 將刪除: {dir_path}")
# [模擬] 將刪除: /tmp/parent/empty
else:
dir_path.rmdir()
print(f"已刪除: {dir_path}")
# 已刪除: /tmp/parent/empty
# 使用示例
# clean_empty_dirs('./data', dry_run=True) # 先預(yù)覽
# clean_empty_dirs('./data', dry_run=False) # 實(shí)際刪除7.5 目錄樹展示
def display_tree(directory, prefix='', level=0, max_level=3):
"""以樹形結(jié)構(gòu)顯示目錄內(nèi)容"""
if level > max_level:
return
path = Path(directory)
items = sorted(path.iterdir(), key=lambda x: (not x.is_dir(), x.name))
for i, item in enumerate(items):
is_last = (i == len(items) - 1)
connector = '└── ' if is_last else '├── '
print(f"{prefix}{connector}{item.name}{'/' if item.is_dir() else ''}")
if item.is_dir():
extension = ' ' if is_last else '│ '
display_tree(item, prefix + extension, level + 1, max_level)
# 使用示例
print("項(xiàng)目目錄結(jié)構(gòu):")
display_tree('/home/user/project', max_level=2)
# 項(xiàng)目目錄結(jié)構(gòu):
# ├── docs/
# │ ├── readme.md
# │ └── api/
# │ └── index.html
# ├── src/
# │ ├── main.py
# │ └── utils.py
# └── tests/
# └── test_main.py8. Path 對(duì)象屬性速查表
| 屬性/方法 | 說明 | 示例 |
|---|---|---|
.name | 文件名(含擴(kuò)展名) | 'file.tar.gz' |
.stem | 文件名(不含擴(kuò)展名) | 'file.tar' |
.suffix | 最后一個(gè)擴(kuò)展名 | '.gz' |
.suffixes | 所有擴(kuò)展名列表 | ['.tar', '.gz'] |
.parent | 父目錄 | '/home/user' |
.parents | 所有祖先(可索引) | [Path('/home'), Path('/')] |
.anchor | 根目錄部分 | '/' 或 'C:\\' |
.absolute() | 絕對(duì)路徑 | '/home/user/file.txt' |
.resolve() | 解析后的絕對(duì)路徑 | '/home/user/file.txt' |
.exists() | 是否存在 | True |
.is_file() | 是否為文件 | True |
.is_dir() | 是否為目錄 | False |
.is_absolute() | 是否絕對(duì)路徑 | True |
.is_symlink() | 是否符號(hào)鏈接 | False |
.stat() | 文件狀態(tài)信息 | os.stat_result |
.glob(pattern) | 匹配模式(非遞歸) | 生成器 |
.rglob(pattern) | 遞歸匹配 | 生成器 |
.iterdir() | 遍歷目錄 | 生成器 |
.mkdir() | 創(chuàng)建目錄 | - |
.rmdir() | 刪除空目錄 | - |
.unlink() | 刪除文件 | - |
.rename(target) | 重命名/移動(dòng) | - |
.read_text() | 讀取文本 | 'content' |
.write_text() | 寫入文本 | - |
.read_bytes() | 讀取二進(jìn)制 | b'\x00\x01' |
.write_bytes() | 寫入二進(jìn)制 | - |
.with_name(name) | 替換文件名 | '/home/new.txt' |
.with_suffix(suffix) | 替換擴(kuò)展名 | '/home/file.pdf' |
9. pathlib vs os.path 對(duì)比
# os.path 風(fēng)格
import os.path
folder = 'data'
filename = 'file.txt'
path = os.path.join(folder, filename)
dirname = os.path.dirname(path)
basename = os.path.basename(path)
exists = os.path.exists(path)
size = os.path.getsize(path)
# pathlib 風(fēng)格(更清晰)
from pathlib import Path
path = Path('data') / 'file.txt'
dirname = path.parent
basename = path.name
exists = path.exists()
size = path.stat().st_size10. 最佳實(shí)踐
# ? 推薦:使用 Path 對(duì)象
from pathlib import Path
# 獲取當(dāng)前文件所在目錄
current_dir = Path(__file__).parent
# 項(xiàng)目根目錄(假設(shè)在項(xiàng)目根目錄執(zhí)行)
project_root = Path.cwd()
# 構(gòu)建數(shù)據(jù)路徑
data_path = project_root / 'data' / 'raw_data.csv'
# 檢查并創(chuàng)建目錄
data_path.parent.mkdir(parents=True, exist_ok=True)
# 處理文件
if data_path.exists() and data_path.is_file():
content = data_path.read_text(encoding='utf-8')
# 處理內(nèi)容...
# 遍歷文件
for log_file in project_root.glob('logs/**/*.log'):
if log_file.stat().st_size > 10 * 1024 * 1024: # 大于10MB
archive = log_file.with_suffix('.log.gz')
print(f"歸檔大文件: {log_file} -> {archive}")pathlib 提供了面向?qū)ο蟮摹⒅庇^的路徑操作方式,強(qiáng)烈推薦在新項(xiàng)目中使用它代替 os.path!
到此這篇關(guān)于Python pathlib模塊使用實(shí)例教程的文章就介紹到這了,更多相關(guān)Python pathlib模塊使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- python內(nèi)置模塊pathlib.Path類操作目錄和文件的使用
- Python如何使用pathlib模塊處理文件路徑
- 使用Python?Pathlib模塊一站式解決文件路徑難題
- python編程語(yǔ)言中pathlib模塊簡(jiǎn)介及使用
- 一文帶你掌握Python中pathlib模塊的用法
- Python pathlib模塊實(shí)例詳解
- Python文件路徑處理模塊pathlib示例詳解
- Python pathlib模塊使用方法及實(shí)例解析
- python中pathlib模塊的基本用法與總結(jié)
- 詳談Python3 操作系統(tǒng)與路徑 模塊(os / os.path / pathlib)
相關(guān)文章
python 使用事件對(duì)象asyncio.Event來同步協(xié)程的操作
這篇文章主要介紹了python 使用事件對(duì)象asyncio.Event來同步協(xié)程的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05
Python下opencv使用hough變換檢測(cè)直線與圓
在數(shù)字圖像中,往往存在著一些特殊形狀的幾何圖形,像檢測(cè)馬路邊一條直線,檢測(cè)人眼的圓形等等,有時(shí)我們需要把這些特定圖形檢測(cè)出來,本文就詳細(xì)的介紹了一下方法2021-06-06
Python基于Hypothesis測(cè)試庫(kù)生成測(cè)試數(shù)據(jù)
這篇文章主要介紹了Python基于Hypothesis測(cè)試庫(kù)生成測(cè)試數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
Python實(shí)現(xiàn)抓取城市的PM2.5濃度和排名
本文給大家介紹的是一則使用Python實(shí)現(xiàn)抓取城市的PM2.5數(shù)據(jù)和排名,2015-03-03
Python遠(yuǎn)程控制Windows服務(wù)器的方法詳解
在很多企業(yè)會(huì)使用閑置的 Windows 機(jī)器作為臨時(shí)服務(wù)器,有時(shí)候我們想遠(yuǎn)程調(diào)用里面的程序或查看日志文件。本文分享了利用Python遠(yuǎn)程控制Windows服務(wù)器的方法,感興趣的可以學(xué)習(xí)一下2022-05-05
Matplotlib多子圖使用一個(gè)圖例的實(shí)現(xiàn)
多子圖是Matplotlib中的一個(gè)功能,可以在同一圖形中創(chuàng)建多個(gè)子圖,本文主要介紹了Matplotlib多子圖使用一個(gè)圖例的實(shí)現(xiàn),感興趣的可以了解一下2023-08-08
pycharm運(yùn)行程序時(shí)看不到任何結(jié)果顯示的解決
今天小編就為大家分享一篇pycharm運(yùn)行程序時(shí)看不到任何結(jié)果顯示的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-02-02
Django框架實(shí)現(xiàn)的簡(jiǎn)單分頁(yè)功能示例
這篇文章主要介紹了Django框架實(shí)現(xiàn)的簡(jiǎn)單分頁(yè)功能,在之前一篇留言板之上增加了簡(jiǎn)單分頁(yè)功能,涉及Paginator模塊的簡(jiǎn)單使用技巧,需要的朋友可以參考下2018-12-12

