Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Copy file chọn lọc giữa thư mục trong Python (shutil.copy)

shutil.copy(src, dst) copy file (giữ permission, không giữ metadata như mtime). Dùng copy2() để giữ metadata.

Ví dụ copy list file

import shutil
import os

files = ['file1.txt', 'file2.txt', 'file3.txt']
dest = 'dest_folder'
os.makedirs(dest, exist_ok=True)

for f in files:
    shutil.copy(f, dest)
    print(f"Copied {f} → {dest}")

Các hàm copy trong shutil

HàmChức năng
copy(src, dst)Copy nội dung + permission bits
copy2(src, dst)Copy + metadata (mtime, atime) — khuyến nghị
copyfile(src, dst)Chỉ copy nội dung, dst phải là file
copyfileobj(fsrc, fdst)Copy giữa file object (streaming)
copytree(src, dst)Copy đệ quy toàn bộ thư mục

Copy với pattern (glob)

import glob
for f in glob.glob('*.txt'):
    shutil.copy2(f, 'dest_folder/')