Latest Post

Tăng thứ hạng và truy cập tự nhiên với 10 phương pháp SEO hay nhất Kiếm Tiền Online (mmo): Khái Niệm và Các Hình Thức Phổ Biến

Tiếp tục với loạt hướng dẫn về lập trình Python, trong bài học hôm nay, chúng ta sẽ tìm hiểu cách tạo tệp nén dạng zip bằng Python bằng cách sử dụng thư viện tích hợp có sẵn trong Python 3, không yêu cầu cài đặt thêm, thư viện đó là “zipfile”.

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à một ứng dụng đơn giản để tạo file zip. Nếu bạn muốn thực hiện nhiều tác vụ hơn như nén một thư mục hoặc thêm mật khẩu cho file zip, hãy xem hướng dẫn sử dụng thư viện zipfile ở đây.

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *