Python實現(xiàn)文件/文件夾復(fù)制功能
更新時間:2025年04月01日 08:59:35 作者:ak啊
在數(shù)據(jù)處理和文件管理的日常工作中,我們經(jīng)常需要復(fù)制文件夾及其子文件夾下的特定文件,手動操作不僅效率低下,而且容易出錯,因此,使用編程語言自動化這一任務(wù)顯得尤為重要,所以本文給大家介紹了使用Python實現(xiàn)文件/文件夾復(fù)制功能,需要的朋友可以參考下
一、基礎(chǔ)工具庫介紹
Python標準庫中的shutil
模塊是主要工具:
import shutil import os
二、文件復(fù)制基礎(chǔ)
1. 復(fù)制單個文件
# 保留元數(shù)據(jù)(修改時間等) shutil.copy2('source.txt', 'destination.txt') # 僅復(fù)制內(nèi)容 shutil.copy('source.txt', 'backup/') # 自動保留文件名 # 文件流方式(適合大文件) with open('source.txt', 'rb') as src, open('dest.txt', 'wb') as dst: shutil.copyfileobj(src, dst, length=16*1024) # 16KB緩沖區(qū)
三、目錄復(fù)制進階
1. 簡單目錄復(fù)制
# 復(fù)制整個目錄(目標目錄必須不存在) 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文件和臨時文件 shutil.copytree('src', 'dst', ignore=ignore_patterns('*.pyc', '*.tmp')) # 帶進度回調(diào)的復(fù)制 def copy_progress(src, dst, *, follow_symlinks=True): print(f"Copying {src} => {dst}") shutil.copytree('src', 'dst', copy_function=copy_progress)
四、高級自定義實現(xiàn)
當需要完全控制復(fù)制流程時,可以手動實現(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)
五、異常處理要點
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
的默認實現(xiàn) - 超大文件:使用
copyfileobj
分塊復(fù)制 - 網(wǎng)絡(luò)存儲:增加緩沖區(qū)大小(例如
16*1024*1024
即16MB) - 并行處理:對獨立子目錄使用多線程/多進程
七、完整示例代碼
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)鍵點說明:
- 使用
copy2
而不是copy
可以保留文件元數(shù)據(jù) Path
對象比字符串路徑更安全易用dirs_exist_ok
參數(shù)需要Python 3.8+- 自定義ignore模式支持復(fù)雜過濾邏輯
- 完善的異常處理保證操作可靠性
這種方法可以處理以下復(fù)雜場景:
- 混合文件類型(普通文件/符號鏈接/特殊文件)
- 保留所有文件屬性
- 覆蓋已有內(nèi)容的安全處理
- 靈活的過濾機制
- 跨平臺兼容性(Windows/Unix)
以上就是Python實現(xiàn)文件/文件夾復(fù)制功能的詳細內(nèi)容,更多關(guān)于Python文件/文件夾復(fù)制的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python系統(tǒng)指定文件的查找只輸出目錄下所有文件及文件夾
這篇文章主要介紹了python系統(tǒng)指定文件的查找只輸出目錄下所有文件及文件夾,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-01-01