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

Copy file từ thư mục này sang thư mục khác trong Python (shutil.copy)

Cùng nội dung với bài 1003107743 — shutil.copy() / copy2() dùng cho copy file đơn lẻ hoặc nhiều file trong vòng lặp.

Ví dụ cơ bản

import shutil, os
shutil.copy2('source.txt', 'dest_folder/')  # copy vào thư mục, giữ tên
shutil.copy2('source.txt', 'dest_folder/new_name.txt')  # copy + rename

Copy toàn bộ thư mục (recursive)

shutil.copytree('src_folder', 'dest_folder')
# Python 3.8+: dirs_exist_ok=True cho phép dest đã tồn tại
shutil.copytree('src_folder', 'dest_folder', dirs_exist_ok=True)

Copy lớn (streaming, tiết kiệm RAM)

with open('large.bin', 'rb') as fsrc:
    with open('dest/large.bin', 'wb') as fdst:
        shutil.copyfileobj(fsrc, fdst, length=1024*1024)  # 1MB buffer