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

Cách copy file sang thư mục mới bằng Python?


Module shutil cung cấp hàm copy file và cả thư mục. Copy nhiều file cùng lúc, cần list file muốn copy và lặp copy.

Gọi shutil.copy(source, destination) copy file tại source vào thư mục destination. (Cả hai là string.) Nếu destination là tên file, dùng làm tên mới file copy. Hàm trả về string đường dẫn file đã copy. Ví dụ:

import shutil, os
files = ['file1.txt', 'file2.txt', 'file3.txt']
os.mkdir('my_new_folder')
for f in files:
    shutil.copy(f, 'my_new_folder')