Hướng dẫn how do i make a zip file in python? - làm cách nào để tạo một tệp zip trong python?

Hướng dẫn how do i make a zip file in python? - làm cách nào để tạo một tệp zip trong python?

Trong bài viết này, chúng tôi sẽ thảo luận về cách tạo kho lưu trữ zip từ các tệp hoặc tệp đã chọn từ thư mục dựa trên các bộ lọc.

Mô -đun Zipfile Python cung cấp một lớp zipfile cho các công cụ liên quan đến tệp zip. Hãy để sử dụng điều này để tạo tệp lưu trữ zip.zipfile module provides a ZipFile class for zip file related stuff. Let’s use this to create a zip archive file.

Đầu tiên nhập lớp từ mô -đun, tức là

from zipfile import ZipFile

Các bước & nbsp; là,

Quảng cáo

  • Tạo một zipfile & nbsp; Đối tượng bằng cách chuyển tên tệp và chế độ mới là ‘W W (chế độ ghi). Nó sẽ tạo một tệp zip mới và mở nó trong đối tượng zipfile.
  • Chức năng ghi () trên đối tượng ZipFile để thêm các tệp trong đó.
  • Gọi Đóng () trên đối tượng ZipFile để đóng tệp zip.
# create a ZipFile object
zipObj = ZipFile('sample.zip', 'w')

# Add multiple files to the zip
zipObj.write('sample_file.csv')
zipObj.write('test_1.log')
zipObj.write('test_2.log')

# close the Zip File
zipObj.close()

Nó sẽ tạo một tệp zip ‘sample.zip, & nbsp; với các tập tin đã cho bên trong nó. Chúng ta có thể làm điều tương tự với các trò chơi với Open Open. Nó sẽ tự động đóng tệp zip khi đối tượng zipfile đi ra khỏi phạm vi, tức là. ‘sample.zip’  with given files inside it.
We can do the same thing with “with open” . It will automatically close the zip file when ZipFile object goes out of scope i.e.

# Create a ZipFile Object
with ZipFile('sample2.zip', 'w') as zipObj2:
   # Add multiple files to the zip
   zipObj2.write('sample_file.csv')
   zipObj2.write('test_1.log')
   zipObj2.write('test_2.log')

Tạo một kho lưu trữ zip của một thư mục

Để zip tất cả các nội dung của một thư mục trong kho lưu trữ zip, chúng tôi cần lặp lại tất cả các tệp trong thư mục và các thư mục phụ của nó, & nbsp; sau đó thêm mỗi mục nhập vào tệp zip bằng zipfile.write ()

from zipfile import ZipFile
import os
from os.path import basename

# create a ZipFile object
with ZipFile('sampleDir.zip', 'w') as zipObj:
   # Iterate over all the files in directory
   for folderName, subfolders, filenames in os.walk(dirName):
       for filename in filenames:
           #create complete filepath of file in directory
           filePath = os.path.join(folderName, filename)
           # Add file to zip
           zipObj.write(filePath, basename(filePath))

Nó sẽ zip tất cả các nội dung của một thư mục trong một tệp zip duy nhất i..e & nbsp; ‘sampledir.zip. Nó nội dung sẽ có,

sampleDir/sample_file.csv                      2018-11-30 21:44:46         2829
sampleDir/logs/test_1.log                      2018-11-30 21:44:36         3386
sampleDir/logs/test_2.log                      2018-11-30 21:44:56         3552

Zip đã chọn các tệp từ một thư mục dựa trên bộ lọc hoặc ký tự đại diện

Để zip đã chọn các tệp từ một thư mục, chúng tôi cần kiểm tra điều kiện trên mỗi đường dẫn tệp trong khi lặp trước khi thêm nó vào tệp zip.

Hãy để tạo ra chức năng mà lặp lại trên một thư mục và lọc các nội dung với cuộc gọi lại đã cho. Các tệp vượt qua bộ lọc sẽ chỉ được thêm vào trong zip, tức là

from zipfile import ZipFile
import os
from os.path import basename

# Zip the files from given directory that matches the filter
def zipFilesInDir(dirName, zipFileName, filter):
   # create a ZipFile object
   with ZipFile(zipFileName, 'w') as zipObj:
       # Iterate over all the files in directory
       for folderName, subfolders, filenames in os.walk(dirName):
           for filename in filenames:
               if filter(filename):
                   # create complete filepath of file in directory
                   filePath = os.path.join(folderName, filename)
                   # Add file to zip
                   zipObj.write(filePath, basename(filePath))

Hãy để ZIP chỉ có các tệp CSV từ một thư mục, tức là chuyển hàm Lambda dưới dạng đối số trong đó.

zipFilesInDir('sampleDir', 'sampleDir2.zip', lambda name : 'csv' in name)

Nó sẽ tạo một kho lưu trữ zip ‘Sampledir2.zip, với tất cả các tệp CSV từ thư mục đã cho.

Ví dụ hoàn chỉnh như sau:

from zipfile import ZipFile
import os
from os.path import basename

# Zip the files from given directory that matches the filter
def zipFilesInDir(dirName, zipFileName, filter):
   # create a ZipFile object
   with ZipFile(zipFileName, 'w') as zipObj:
       # Iterate over all the files in directory
       for folderName, subfolders, filenames in os.walk(dirName):
           for filename in filenames:
               if filter(filename):
                   # create complete filepath of file in directory
                   filePath = os.path.join(folderName, filename)
                   # Add file to zip
                   zipObj.write(filePath, basename(filePath))

def main():

    print('*** Create a zip file from multiple files  ')

    #create a ZipFile object
    zipObj = ZipFile('sample.zip', 'w')

    # Add multiple files to the zip
    zipObj.write('sample_file.csv')
    zipObj.write('test_1.log')
    zipObj.write('test_2.log')

    # close the Zip File
    zipObj.close()

    print('*** Create a zip file from multiple files using with ')

    # Create a ZipFile Object
    with ZipFile('sample2.zip', 'w') as zipObj2:
       # Add multiple files to the zip
       zipObj2.write('sample_file.csv')
       zipObj2.write('test_1.log')
       zipObj2.write('test_2.log')

    # Name of the Directory to be zipped
    dirName = 'sampleDir'

    # create a ZipFile object
    with ZipFile('sampleDir.zip', 'w') as zipObj:
       # Iterate over all the files in directory
       for folderName, subfolders, filenames in os.walk(dirName):
           for filename in filenames:
               #create complete filepath of file in directory
               filePath = os.path.join(folderName, filename)
               # Add file to zip
               zipObj.write(filePath)

    print('*** Create a zip archive of only csv files form a directory ***')

    zipFilesInDir('sampleDir', 'sampleDir2.zip', lambda name : 'csv' in name)


if __name__ == '__main__':
   main()

Làm thế nào để bạn tạo một tệp zip trong Python?

Summary..
Để zip toàn bộ thư mục, hãy sử dụng lệnh, SHOWIL.Make_Archive (tên tên, tên, Zip Zip, root_dir).
Để chọn các tệp để sử dụng lệnh ZIP Lệnh Zipfile.Write (tên tệp).

Làm cách nào để zip một tệp duy nhất trong Python?

Để nén các tệp riêng lẻ vào tệp zip, hãy tạo một đối tượng ZipFile mới và thêm các tệp bạn muốn nén bằng phương thức write ().Với zipfile.Zipfile (), chỉ định đường dẫn của tệp zip mới được tạo làm tệp tham số đầu tiên và đặt chế độ tham số thứ hai thành 'w' (viết).create a new ZipFile object and add the files you want to compress with the write() method. With zipfile. ZipFile() , specify the path of a newly created ZIP file as the first parameter file , and set the second parameter mode to 'w' (write).

Làm thế nào để bạn tạo một tệp zip?

Nhấp chuột phải vào tệp hoặc thư mụcĐể đặt nhiều tệp vào thư mục ZIP, chọn tất cả các tệp trong khi nhấn nút Ctrl.Sau đó, nhấp chuột phải vào một trong các tệp, hãy di chuyển con trỏ của bạn qua tùy chọn Gửi đến Tùy chọn và chọn thư mục nén (Zipped). Select “Compressed (zipped) folder”. To place multiple files into a zip folder, select all of the files while hitting the Ctrl button. Then, right-click on one of the files, move your cursor over the “Send to” option and select “Compressed (zipped) folder”.

Làm cách nào để tạo một tệp zip trong pycharm?

Đi vào bên trong thư mục dự án Pycharm của bạn -> Chọn tất cả -> Nhấp chuột phải -> Gửi đến nén (ZIP).Điều này có thể dẫn đến việc bao gồm một số thư mục không cần thiết (__pycache__,. Ý tưởng), nhưng sẽ không ảnh hưởng đến việc thực hiện chương trình.Nếu cần, bạn có thể bỏ qua hai thư mục đó trong khi tạo zip.. This may result in the inclusion of some unneeded directories (__pycache__, . idea), but would not affect the program execution. If needed, you may skip those two directories while creating the zip.