最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python  pathlib模塊使用實(shí)例教程

 更新時(shí)間:2026年05月19日 09:51:41   作者:70asunflower  
本文介紹了pathlib模塊,作為os.path的升級(jí),提供了面向?qū)ο蟮奈募窂教幚矸绞?文章主要介紹了pathlib的基本用法,結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧

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.md

2. 路徑拼接與拆分

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/html

2.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.conf

3. 路徑檢查與屬性

# 假設(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)  # True

4. 目錄操作

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())  # True

6. 文件屬性和信息

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.txt

7. 實(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.py

8. 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_size

10. 最佳實(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)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

谷城县| 府谷县| 广水市| 社旗县| 杨浦区| 宜城市| 诏安县| 尚志市| 洮南市| 石林| 友谊县| 龙岩市| 崇明县| 青河县| 屏东市| 蕲春县| 洪洞县| 栾城县| 玉树县| 含山县| 馆陶县| 会宁县| 建瓯市| 台湾省| 青州市| 凯里市| 长阳| 会泽县| 襄汾县| 长岛县| 徐汇区| 新兴县| 龙江县| 阳谷县| 宣恩县| 自贡市| 象州县| 黄山市| 当涂县| 义马市| 怀柔区|