一文帶你掌握Python3中文件和文件夾操作的核心模塊
本文整理 Python3 核心文件 / 文件夾操作,聚焦與os、os.path、shutil,以及傳統(tǒng)模塊與 Python3.4+ 新增的pathlib和現(xiàn)代化模塊,涵蓋路徑處理、文件讀寫、目錄管理、批量操作等!
一、核心模塊與環(huán)境說明
1. 模塊特性對比
| 模塊 | 核心優(yōu)勢 | 適用場景 | 版本要求 |
|---|---|---|---|
os | 系統(tǒng)底層操作,功能全面 | 進程管理、系統(tǒng)命令調用、基礎文件操作 | Python3 全版本 |
os.path | 路徑字符串處理,跨平臺兼容 | 路徑拼接、判斷、拆分 | Python3 全版本 |
shutil | 高級文件操作,封裝常用功能 | 復制、移動、刪除、壓縮 | Python3 全版本 |
pathlib | 面向對象 API,語法簡潔,可讀性強 | 路徑處理、文件讀寫、目錄遍歷 | Python3.4+ |
2. 基礎導入語句
# 傳統(tǒng)模塊(兼容所有Python3版本) import os import os.path as op import shutil # 現(xiàn)代化模塊(Python3.4+推薦) from pathlib import Path
二、路徑處理操作
1. 傳統(tǒng)方式(os + os.path)
# 1. 獲取當前工作目錄
current_dir = os.getcwd()
print("當前目錄:", current_dir)
# 2. 路徑拼接(避免硬編碼分隔符)
file_path = op.join(current_dir, "data", "test.txt")
print("拼接路徑:", file_path) # 輸出: 跨平臺自動適配(Windows\,Linux/Mac/)
# 3. 路徑拆解
print("目錄名:", op.dirname(file_path)) # 輸出: 父目錄路徑
print("文件名:", op.basename(file_path)) # 輸出: test.txt
print("擴展名:", op.splitext(file_path)[1]) # 輸出: .txt
print("文件名(無擴展名):", op.splitext(op.basename(file_path))[0]) # 輸出: test
# 4. 路徑判斷
print("是否為文件:", op.isfile(file_path))
print("是否為目錄:", op.isdir(current_dir))
print("路徑是否存在:", op.exists(file_path))
print("是否為絕對路徑:", op.isabs(file_path))
# 5. 獲取絕對路徑
abs_path = op.abspath("relative/path")
print("絕對路徑:", abs_path)
2. 現(xiàn)代化方式(pathlib)
# 1. 創(chuàng)建路徑對象(推薦方式)
current_dir = Path.cwd() # 獲取當前目錄
file_path = current_dir / "data" / "test.txt" # 路徑拼接(支持/運算符)
print("路徑對象:", file_path) # 自動適配系統(tǒng)路徑格式
# 2. 路徑屬性(直觀易用)
print("目錄名:", file_path.parent) # 父目錄(可鏈式調用:file_path.parent.parent)
print("文件名:", file_path.name) # 完整文件名:test.txt
print("擴展名:", file_path.suffix) # 擴展名:.txt
print("文件名(無擴展名):", file_path.stem) # 文件名:test
print("絕對路徑:", file_path.absolute())
# 3. 路徑判斷(面向對象方法)
print("是否為文件:", file_path.is_file())
print("是否為目錄:", current_dir.is_dir())
print("路徑是否存在:", file_path.exists())
print("是否為絕對路徑:", file_path.is_absolute())
# 4. 路徑匹配(支持glob模式)
print("匹配所有txt文件:", list(current_dir.glob("*.txt")))
print("遞歸匹配所有py文件:", list(current_dir.rglob("*.py"))) # Python3.5+
三、文件操作
1. 基礎讀寫
# 1. 文本文件寫入(覆蓋模式)
with open("test.txt", "w", encoding="utf-8") as f:
f.write("Python文件操作備忘錄\n")
f.writelines(["第一行內容\n", "第二行內容\n"])
# 2. 文本文件讀取
with open("test.txt", "r", encoding="utf-8") as f:
content = f.read() # 讀取全部內容
# content = f.readline() # 讀取一行
# content = f.readlines() # 讀取所有行到列表
# 3. 二進制文件操作(如圖片、視頻)
with open("image.jpg", "rb") as f:
binary_data = f.read() # 讀取二進制數(shù)據(jù)
with open("image_copy.jpg", "wb") as f:
f.write(binary_data) # 寫入二進制數(shù)據(jù)
# 4. 文件指針控制(seek/tell)
with open("test.txt", "r", encoding="utf-8") as f:
f.seek(10) # 移動到第10字節(jié)位置
print("當前指針位置:", f.tell()) # 返回當前指針位置
f.seek(0, 2) # 移動到文件末尾(適合追加前定位)
2. pathlib 簡化讀寫
# 1. 文本文件讀寫(一行搞定)
file = Path("test_pathlib.txt")
file.write_text("pathlib 簡化文件操作\n", encoding="utf-8") # 寫入
content = file.read_text(encoding="utf-8") # 讀取
print("讀取內容:", content)
# 2. 二進制文件讀寫
bin_file = Path("image_copy.jpg")
bin_file.write_bytes(binary_data) # 寫入二進制
read_bin = bin_file.read_bytes() # 讀取二進制
# 3. 逐行讀?。ù笪募押茫?
with file.open("r", encoding="utf-8") as f:
for line in f:
print(line.strip())
四、目錄操作(創(chuàng)建 / 刪除 / 遍歷)
1. 傳統(tǒng)方式(os + shutil)
# 1. 創(chuàng)建目錄
os.mkdir("new_dir") # 創(chuàng)建單級目錄(父目錄不存在則報錯)
os.makedirs("parent_dir/child_dir", exist_ok=True) # 創(chuàng)建多級目錄(Python3.2+支持exist_ok)
# 2. 刪除目錄
os.rmdir("new_dir") # 刪除空目錄(非空則報錯)
shutil.rmtree("parent_dir") # 強制刪除目錄(含所有子文件/目錄,慎用!)
# 3. 目錄遍歷
# 方式1:列出目錄內容(僅當前級)
for name in os.listdir("target_dir"):
full_path = op.join("target_dir", name)
if op.isfile(full_path):
print("文件:", name)
else:
print("目錄:", name)
# 方式2:遞歸遍歷目錄(Python3.5+)
for root, dirs, files in os.walk("target_dir"):
print(f"當前目錄: {root}")
print(f"子目錄: {dirs}")
print(f"文件: {files}")
2. 現(xiàn)代化方式(pathlib)
# 1. 創(chuàng)建目錄
Path("new_dir").mkdir(exist_ok=True) # 單級目錄
Path("parent_dir/child_dir").mkdir(parents=True, exist_ok=True) # 多級目錄(parents=True必選)
# 2. 刪除目錄
Path("new_dir").rmdir() # 刪除空目錄
shutil.rmtree("parent_dir") # pathlib無強制刪除,需配合shutil
# 3. 目錄遍歷
# 方式1:遍歷當前級內容
for item in Path("target_dir").iterdir():
if item.is_file():
print("文件:", item.name)
else:
print("目錄:", item.name)
# 方式2:遞歸遍歷(推薦,簡潔直觀)
for file in Path("target_dir").rglob("*"):
if file.is_file():
print("遞歸找到文件:", file)
五、高級操作
1. 文件復制與移動
# 1. 文件復制
shutil.copy("source.txt", "dest.txt") # 復制文件內容和權限
shutil.copy2("source.txt", "dest_dir/") # 復制文件+保留元數(shù)據(jù)(創(chuàng)建時間等)
shutil.copyfile("source.bin", "dest.bin") # 僅復制文件內容(無權限)
# 2. 目錄復制(遞歸復制所有內容)
shutil.copytree("source_dir", "dest_dir", dirs_exist_ok=True) # Python3.8+支持覆蓋
# 3. 文件/目錄移動(剪切)
shutil.move("source.txt", "target_dir/") # 移動文件到目錄
shutil.move("old_dir", "new_dir") # 重命名目錄(目標不存在)或移動到目標目錄
# 4. 壓縮與解壓
# 壓縮(創(chuàng)建zip包)
shutil.make_archive("archive", "zip", root_dir="target_dir") # 生成archive.zip
# 解壓(提取zip包)
shutil.unpack_archive("archive.zip", extract_dir="unpack_dir")
2. 批量文件處理
# 場景1:按擴展名分類文件(如圖片、文檔)
from pathlib import Path
import shutil
ext_map = {
".jpg": "Images",
".png": "Images",
".pdf": "Documents",
".docx": "Documents",
".mp3": "Music"
}
source_dir = Path(".")
for file in source_dir.iterdir():
if file.is_file() and file.suffix in ext_map:
target_dir = Path(ext_map[file.suffix])
target_dir.mkdir(exist_ok=True) # 確保目標目錄存在
shutil.move(file, target_dir / file.name) # 移動文件
print(f"已移動: {file.name} -> {target_dir.name}")
# 場景2:批量重命名文件(如添加前綴)
for i, file in enumerate(Path("images").glob("*.jpg")):
new_name = f"photo_{i:03d}{file.suffix}" # 生成001、002格式
file.rename(file.parent / new_name)
print(f"重命名: {file.name} -> {new_name}")
# 場景3:統(tǒng)計目錄下文件大小
def get_dir_size(dir_path):
total_size = 0
for file in Path(dir_path).rglob("*"):
if file.is_file():
total_size += file.stat().st_size # 獲取文件大?。ㄗ止?jié))
return total_size / (1024 * 1024) # 轉換為MB
print(f"目錄總大小: {get_dir_size('target_dir'):.2f} MB")
六、避坑指南
路徑分隔符問題:永遠使用 os.path.join() 或 pathlib 的 / 運算符拼接路徑,避免直接寫死 \ 或 /,確??缙脚_兼容;
文件編碼規(guī)范:讀寫文本文件時必須指定 encoding="utf-8",避免默認編碼導致中文亂碼(Windows 默認 gbk,Linux/Mac 默認 utf-8);
資源釋放原則:始終使用 with 語句操作文件,自動關閉文件句柄,避免資源泄露;
刪除操作警告:shutil.rmtree() 和 os.remove() 是不可逆操作,生產(chǎn)環(huán)境需添加二次確認邏輯,或先備份再刪除;
版本兼容性:
pathlib.rglob()需 Python3.5+;shutil.copytree(dirs_exist_ok=True)需 Python3.8+;- 若需兼容低版本,優(yōu)先使用
os+os.path組合;
大文件處理:避免使用 read() 一次性讀取超大文件(占用內存),推薦 readline() 逐行讀取或 pathlib 迭代器;
權限問題:復制 / 移動文件時注意權限繼承,shutil.copy2() 保留元數(shù)據(jù)更適合需要追溯文件歷史的場景。
以上就是一文帶你掌握Python3中文件和文件夾操作的核心模塊的詳細內容,更多關于Python3文件和文件夾操作的資料請關注腳本之家其它相關文章!
相關文章
基于python+opencv調用電腦攝像頭實現(xiàn)實時人臉眼睛以及微笑識別
這篇文章主要為大家詳細介紹了基于python+opencv調用電腦攝像頭實現(xiàn)實時人臉眼睛以及微笑識別,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09
python Boltons庫實用功能探索(深度復制類型檢查重試機制)
這篇文章主要為大家介紹了python Boltons庫實用功能探索包含深度復制類型檢查重試機制及數(shù)據(jù)結構轉換實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
pycharm三個有引號不能自動生成函數(shù)注釋的問題
這篇文章主要介紹了解決pycharm三個有引號不能自動生成函數(shù)注釋的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02
python安裝numpy&安裝matplotlib& scipy的教程
下面小編就為大家?guī)硪黄猵ython安裝numpy&安裝matplotlib& scipy的教程。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11
Python實現(xiàn)跨平臺桌面應用程序開發(fā)的完整指南
在當今軟件開發(fā)領域,跨平臺應用程序開發(fā)變得越來越重要,下面我們就來探討使用Python進行跨平臺桌面應用程序開發(fā)的主要框架,工具和最佳實踐吧2025-04-04

