Python實(shí)現(xiàn)文件/文件夾復(fù)制功能
一、基礎(chǔ)工具庫(kù)介紹
Python標(biāo)準(zhǔn)庫(kù)中的shutil模塊是主要工具:
import shutil import os
二、文件復(fù)制基礎(chǔ)
1. 復(fù)制單個(gè)文件
# 保留元數(shù)據(jù)(修改時(shí)間等)
shutil.copy2('source.txt', 'destination.txt')
# 僅復(fù)制內(nèi)容
shutil.copy('source.txt', 'backup/') # 自動(dòng)保留文件名
# 文件流方式(適合大文件)
with open('source.txt', 'rb') as src, open('dest.txt', 'wb') as dst:
shutil.copyfileobj(src, dst, length=16*1024) # 16KB緩沖區(qū)
三、目錄復(fù)制進(jìn)階
1. 簡(jiǎn)單目錄復(fù)制
# 復(fù)制整個(gè)目錄(目標(biāo)目錄必須不存在)
shutil.copytree('src_dir', 'dst_dir')
# 允許覆蓋已存在目錄(Python 3.8+)
shutil.copytree('src', 'existing_dir', dirs_exist_ok=True)
2. 自定義復(fù)制過(guò)程
def ignore_patterns(*patterns):
def _ignore(path, names):
ignored = []
for pattern in patterns:
ignored.extend(fnmatch.filter(names, pattern))
return set(ignored)
return _ignore
# 排除.pyc文件和臨時(shí)文件
shutil.copytree('src', 'dst', ignore=ignore_patterns('*.pyc', '*.tmp'))
# 帶進(jìn)度回調(diào)的復(fù)制
def copy_progress(src, dst, *, follow_symlinks=True):
print(f"Copying {src} => {dst}")
shutil.copytree('src', 'dst', copy_function=copy_progress)
四、高級(jí)自定義實(shí)現(xiàn)
當(dāng)需要完全控制復(fù)制流程時(shí),可以手動(dòng)實(shí)現(xiàn):
def deep_copy(src, dst, symlinks=False):
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
for item in os.listdir(src):
src_path = os.path.join(src, item)
dst_path = os.path.join(dst, item)
if os.path.isdir(src_path):
deep_copy(src_path, dst_path, symlinks)
else:
if os.path.exists(dst_path):
if os.path.samefile(src_path, dst_path):
continue
os.remove(dst_path)
if symlinks and os.path.islink(src_path):
linkto = os.readlink(src_path)
os.symlink(linkto, dst_path)
else:
shutil.copy2(src_path, dst_path)
五、異常處理要點(diǎn)
try:
shutil.copytree('src', 'dst')
except shutil.Error as e:
print(f'Directory not copied. Error: {e}')
except OSError as e:
print(f'OSError: {e.strerror}')
六、性能優(yōu)化建議
- 批量小文件:使用
shutil.copytree的默認(rèn)實(shí)現(xiàn) - 超大文件:使用
copyfileobj分塊復(fù)制 - 網(wǎng)絡(luò)存儲(chǔ):增加緩沖區(qū)大?。ɡ?code>16*1024*1024即16MB)
- 并行處理:對(duì)獨(dú)立子目錄使用多線程/多進(jìn)程
七、完整示例代碼
import shutil
import os
from pathlib import Path
def smart_copy(src, dst, overwrite=False, ignore=None):
"""智能復(fù)制器"""
src = Path(src)
dst = Path(dst)
if src.is_file():
if dst.is_dir():
dst = dst / src.name
if dst.exists():
if overwrite:
dst.unlink()
else:
raise FileExistsError(f"{dst} already exists")
shutil.copy2(str(src), str(dst))
return
if not src.is_dir():
raise ValueError("Source path invalid")
if dst.exists():
if overwrite:
if dst.is_dir():
shutil.rmtree(dst)
else:
dst.unlink()
else:
raise FileExistsError(f"{dst} already exists")
shutil.copytree(
str(src),
str(dst),
symlinks=True,
ignore=ignore,
copy_function=shutil.copy2,
dirs_exist_ok=overwrite
)
# 使用示例
smart_copy(
'/data/project',
'/backup/project_2024',
overwrite=True,
ignore=shutil.ignore_patterns('*.log', 'temp')
)
關(guān)鍵點(diǎn)說(shuō)明:
- 使用
copy2而不是copy可以保留文件元數(shù)據(jù) Path對(duì)象比字符串路徑更安全易用dirs_exist_ok參數(shù)需要Python 3.8+- 自定義ignore模式支持復(fù)雜過(guò)濾邏輯
- 完善的異常處理保證操作可靠性
這種方法可以處理以下復(fù)雜場(chǎng)景:
- 混合文件類型(普通文件/符號(hào)鏈接/特殊文件)
- 保留所有文件屬性
- 覆蓋已有內(nèi)容的安全處理
- 靈活的過(guò)濾機(jī)制
- 跨平臺(tái)兼容性(Windows/Unix)
以上就是Python實(shí)現(xiàn)文件/文件夾復(fù)制功能的詳細(xì)內(nèi)容,更多關(guān)于Python文件/文件夾復(fù)制的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- Python pyttsx3庫(kù)實(shí)現(xiàn)文本轉(zhuǎn)語(yǔ)音功能的示例
- Python調(diào)用JAR包的類和方法詳細(xì)指南
- Python實(shí)現(xiàn)無(wú)痛修改第三方庫(kù)源碼的方法詳解
- Python如何使用__slots__實(shí)現(xiàn)節(jié)省內(nèi)存和性能優(yōu)化
- Python+PyQt5實(shí)現(xiàn)多屏幕協(xié)同播放功能
- Python中隨機(jī)休眠技術(shù)原理與應(yīng)用詳解
- 基于Python開(kāi)發(fā)高效文件搜索與內(nèi)容匹配工具
- Python模塊Uvicorn實(shí)戰(zhàn)
相關(guān)文章
Python實(shí)現(xiàn)類的創(chuàng)建與使用方法示例
這篇文章主要介紹了Python實(shí)現(xiàn)類的創(chuàng)建與使用方法,結(jié)合簡(jiǎn)單計(jì)算器功能實(shí)例分析了Python類的定義與使用方法,需要的朋友可以參考下2017-07-07
Python中常見(jiàn)路徑算法的原理與實(shí)現(xiàn)詳解
在計(jì)算機(jī)科學(xué)中,路徑算法是解決許多實(shí)際問(wèn)題的核心工具,本文介紹了Python中三種常見(jiàn)的路徑算法及其實(shí)現(xiàn),幫助讀者快速上手并理解這些算法的原理和應(yīng)用2026-04-04
Python從Manim中提取表格/坐標(biāo)系并轉(zhuǎn)GIF的四種高效方案
在數(shù)據(jù)可視化和數(shù)學(xué)動(dòng)畫創(chuàng)作中,我們經(jīng)常需要將 Manim 動(dòng)畫中的表格、坐標(biāo)系等核心元素單獨(dú)導(dǎo)出為 GIF,本文整理了四種高效方案,每種方案僅提供核心代碼,聚焦關(guān)鍵實(shí)現(xiàn)邏輯,需要的朋友可以參考下2025-08-08
python按順序重命名文件并分類轉(zhuǎn)移到各個(gè)文件夾中的實(shí)現(xiàn)代碼
這篇文章主要介紹了python按順序重命名文件并分類轉(zhuǎn)移到各個(gè)文件夾中,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07
python使用ctypes調(diào)用擴(kuò)展模塊的實(shí)例方法
在本篇文章里小編給大家整理的是一篇關(guān)于python使用ctypes調(diào)用擴(kuò)展模塊的實(shí)例方法內(nèi)容,需要的朋友們可以學(xué)習(xí)參考下。2020-01-01

