如何在Python中使用ZIPFILE模組壓縮檔案。
問題
你想在Python中建立壓縮檔案。
介紹
ZIP檔案可以儲存許多其他檔案的壓縮內容。壓縮檔案會減小其在磁碟上的大小,這在透過網際網路或使用Control-m AFT、Connect Direct甚至scp在系統之間傳輸檔案時非常有用。
Python程式使用zipfile模組中的函式建立ZIP檔案。
操作步驟...
1. 我們將使用zipfile和io包。如果系統上缺少任何包,請使用pip安裝它們。如果不確定,請使用pip freeze命令驗證包。
2. 我們將編寫一個函式來將樣本資料寫入檔案。下面的write_data_to_files函式將資料作為輸入,並在當前目錄中建立同名檔案。
示例
# Function : write_data_to_files
def write_data_to_files(inp_data, file_name):
"""
function : create a csv file with the data passed to this code
args : inp_data : data to be written to the target file
file_name : target file name to store the data
return : none
assumption : File to be created and this code are in same directory.
"""
print(f" *** Writing the data to - {file_name}")
throwaway_storage = io.StringIO(inp_data)
with open(file_name, 'w') as f:
for line in throwaway_storage:
f.write(line)3. 我們現在將編寫一個名為file_compress的函式來壓縮上面步驟中建立的檔案。此函式接受檔案列表,遍歷它們並將它們壓縮到一個zip檔案中。每一步的詳細解釋都已在註釋中提供。
要建立您自己的壓縮ZIP檔案,必須透過將'w'作為第二個引數來以寫入模式開啟ZipFile物件。
當您將路徑傳遞給ZipFile物件的write()方法時,Python將壓縮該路徑下的檔案並將其新增到ZIP檔案中。
write()方法的第一個引數是要新增的檔名的字串。
第二個引數是壓縮型別引數,它告訴計算機應該使用什麼演算法來壓縮檔案。
示例
# Function : file_compress
def file_compress(inp_file_names, out_zip_file):
"""
function : file_compress
args : inp_file_names : list of filenames to be zipped
out_zip_file : output zip file
return : none
assumption : Input file paths and this code is in same directory.
"""
# Select the compression mode ZIP_DEFLATED for compression
# or zipfile.ZIP_STORED to just store the file
compression = zipfile.ZIP_DEFLATED
print(f" *** Input File name passed for zipping - {inp_file_names}")
# create the zip file first parameter path/name, second mode
print(f' *** out_zip_file is - {out_zip_file}')
zf = zipfile.ZipFile(out_zip_file, mode="w")
try:
for file_to_write in inp_file_names:
# Add file to the zip file
# first parameter file to zip, second filename in zip
print(f' *** Processing file {file_to_write}')
zf.write(file_to_write, file_to_write, compress_type=compression)
except FileNotFoundError as e:
print(f' *** Exception occurred during zip process - {e}')
finally:
# Don't forget to close the file!
zf.close()4. 我們將呼叫函式來建立兩個csv檔案,然後將它們壓縮。我們將贏得超過1個大滿貫賽冠軍的網球運動員資料寫入一個檔案 - temporary_file1_for_zip.csv,並將贏得1個或少於1個大滿貫賽冠軍的網球運動員資料寫入另一個檔案temporary_file1_for_zip.csv。然後,我們將這兩個檔案壓縮到temporary.zip檔案中。
示例
import zipfile import io import pandas as pd file_name1 = "temporary_file1_for_zip.csv" file_name2 = "temporary_file2_for_zip.csv" file_name_list = [file_name1, file_name2] zip_file_name = "temporary.zip" # data for file 1 file_data_1 = """ player,titles Federer,20 Nadal,20 Djokovic,17 Murray,3 """ # data for file 2 file_data_2 = """ player,titles Theim,1 Zverev,0 Medvedev,0 Rublev,0 """ # write the file_data to file_name write_data_to_files(file_data_1, file_name1) write_data_to_files(file_data_2, file_name2) # zip the file_name to zip_file_name file_compress(file_name_list, zip_file_name)
示例
5. 將上面步驟中討論的所有內容整合在一起。
# Define the data
# let us create a zip file with a single file
import zipfile
import io
import pandas as pd
# Function : write_data_to_files
def write_data_to_files(inp_data, file_name):
"""
function : create a csv file with the data passed to this code
args : inp_data : data to be written to the target file
file_name : target file name to store the data
return : none
assumption : File to be created and this code are in same directory.
"""
print(f" *** Writing the data to - {file_name}")
throwaway_storage = io.StringIO(inp_data)
with open(file_name, 'w') as f:
for line in throwaway_storage:
f.write(line)
# Function : file_compress
def file_compress(inp_file_names, out_zip_file):
"""
function : file_compress
args : inp_file_names : list of filenames to be zipped
out_zip_file : output zip file
return : none
assumption : Input file paths and this code is in same directory.
"""
# Select the compression mode ZIP_DEFLATED for compression
# or zipfile.ZIP_STORED to just store the file
compression = zipfile.ZIP_DEFLATED
print(f" *** Input File name passed for zipping - {inp_file_names}")
# create the zip file first parameter path/name, second mode
print(f' *** out_zip_file is - {out_zip_file}')
zf = zipfile.ZipFile(out_zip_file, mode="w")
try:
for file_to_write in inp_file_names:
# Add file to the zip file
# first parameter file to zip, second filename in zip
print(f' *** Processing file {file_to_write}')
zf.write(file_to_write, file_to_write, compress_type=compression)
except FileNotFoundError as e:
print(f' *** Exception occurred during zip process - {e}')
finally:
# Don't forget to close the file!
zf.close()
# __main__ program
if __name__ == '__main__':
# Define your file name and data
file_name1 = "temporary_file1_for_zip.csv"
file_name2 = "temporary_file2_for_zip.csv"
file_name_list = [file_name1, file_name2]
zip_file_name = "temporary.zip"
file_data_1 = """
player,titles
Federer,20
Nadal,20
Djokovic,17
Murray,3
"""
file_data_2 = """
player,titles
Theim,1
Zverev,0
Medvedev,0
Rublev,0
"""
# write the file_data to file_name
write_data_to_files(file_data_1, file_name1)
write_data_to_files(file_data_2, file_name2)
# zip the file_name to zip_file_name
file_compress(file_name_list, zip_file_name)*** Writing the data to - temporary_file1_for_zip.csv *** Writing the data to - temporary_file2_for_zip.csv *** Input File name passed for zipping - ['temporary_file1_for_zip.csv', 'temporary_file2_for_zip.csv'] *** out_zip_file is - temporary.zip *** Processing file temporary_file1_for_zip.csv *** Processing file temporary_file2_for_zip.csv
輸出
執行上述程式碼後,輸出結果為:
temporary_file1_for_zip.csv已建立在當前目錄中。
temporary_file2_for_zip.csv已建立在當前目錄中。
temporary.zip檔案已建立在當前目錄中。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP