Nối tiếp tutorial về lập trình Python, hôm nay chúng ta sẽ học cách tạo ra file zip bằng cách sử dụng Python, thông qua thư viện zipfile. Thư viện này là build-in của Python 3 nên các bạn không cần phải thực hiện cài đặt.
Tạo File Zip sử dụng Python
Đầu tiên là import thư viện filezip
import zipfile
Lựa chọn mode để nén file zip
# Select the compression mode ZIP_DEFLATED for compression
# or zipfile.ZIP_STORED to just store the file
try:
import zlib
compression = zipfile.ZIP_DEFLATED
except Exception as ex:
compression = zipfile.ZIP_STORED
print(ex)
Tạo file Zip với đường dẫn và mode (w – write, a – append)
# create the zip file first parameter path/name, second mode
zf = zipfile.ZipFile('vinasupport.com.zip', mode='w')
Thêm file vào file zip vừa tạo
# Add file to the zip file
# first parameter file to zip, second filename in zip
zf.write('vinasupport.com.txt', 'vinasupport.com.txt', compress_type=compression
Close file
# Don't forget to close the file! zf.close()
Vậy đoạn code đầy đủ sẽ là:
import zipfile
# Select the compression mode ZIP_DEFLATED for compression
# or zipfile.ZIP_STORED to just store the file
try:
import zlib
compression = zipfile.ZIP_DEFLATED
except Exception as ex:
compression = zipfile.ZIP_STORED
print(ex)
# create the zip file first parameter path/name, second mode
zf = zipfile.ZipFile('vinasupport.com.zip', mode='w')
# Add file to the zip file
# first parameter file to zip, second filename in zip
zf.write('vinasupport.com.txt', 'vinasupport.com.txt', compress_type=compression)
# Don't forget to close the file!
zf.close()
Kết quả
Sau khi chạy đoạn code trên chúng ta đã tạo thành công file zip

Đây là chương trình tạo file zip đơn giản, các bạn muốn làm nhiều thư hơn như zip folder, tạo mật khẩu cho file zip thì vui lòng tham khảo hướng dẫn sử dụng thư viện zipfile ở đây.
Nguồn vinasupport.com