Python實(shí)現(xiàn)文件/文件夾復(fù)制功能
一、基礎(chǔ)工具庫介紹
Python標(biāo)準(zhǔn)庫中的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ù)制過程
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)說明:
- 使用
copy2
而不是copy
可以保留文件元數(shù)據(jù) Path
對(duì)象比字符串路徑更安全易用dirs_exist_ok
參數(shù)需要Python 3.8+- 自定義ignore模式支持復(fù)雜過濾邏輯
- 完善的異常處理保證操作可靠性
這種方法可以處理以下復(fù)雜場(chǎng)景:
- 混合文件類型(普通文件/符號(hào)鏈接/特殊文件)
- 保留所有文件屬性
- 覆蓋已有內(nèi)容的安全處理
- 靈活的過濾機(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庫實(shí)現(xiàn)文本轉(zhuǎn)語音功能的示例
- Python調(diào)用JAR包的類和方法詳細(xì)指南
- Python實(shí)現(xiàn)無痛修改第三方庫源碼的方法詳解
- Python如何使用__slots__實(shí)現(xiàn)節(jié)省內(nèi)存和性能優(yōu)化
- Python+PyQt5實(shí)現(xiàn)多屏幕協(xié)同播放功能
- Python中隨機(jī)休眠技術(shù)原理與應(yīng)用詳解
- 基于Python開發(fā)高效文件搜索與內(nèi)容匹配工具
- Python模塊Uvicorn實(shí)戰(zhàn)
相關(guān)文章
python系統(tǒng)指定文件的查找只輸出目錄下所有文件及文件夾
這篇文章主要介紹了python系統(tǒng)指定文件的查找只輸出目錄下所有文件及文件夾,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-01-01Python異常處理機(jī)制結(jié)構(gòu)實(shí)例解析
這篇文章主要介紹了Python異常處理機(jī)制結(jié)構(gòu)實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07Python中pytest的參數(shù)化實(shí)例解析
這篇文章主要介紹了Python中pytest的參數(shù)化實(shí)例解析,pytest是一個(gè)非常成熟的全功能的Python測(cè)試框架,主要有簡(jiǎn)單靈活,容易上手,支持參數(shù)化等特點(diǎn),需要的朋友可以參考下2023-07-07Pandas中運(yùn)行速度優(yōu)化的常用方法介紹
這篇文章主要為大家詳細(xì)介紹了幾種pandas中常用到的方法,對(duì)于這些方法使用存在哪些需要注意的問題,以及如何對(duì)它們進(jìn)行速度提升,需要的小伙伴可以參考下2025-03-03