我正在開發一個 Flask 應用程式以將 zip 檔案回傳給目錄(一堆照片)的用戶,但我不想在回傳的 zip 中包含我的服務器目錄結構。目前,我有這個:
def return_zip():
dir_to_send = '/dir/to/the/files'
base_path = pathlib.Path(dir_to_send)
data = io.BytesIO()
with zipfile.ZipFile(data, mode='w') as z:
for f_name in base_path.iterdir():
z.write(f_name)
data.seek(0)
return send_file(data, mimetype='application/zip', as_attachment=True, attachment_filename='data.zip')
這對于創建和回傳 zip 非常有用,但該檔案包含我的服務器的結構,即
/dir/to/the/files/image.jpg, image1.jpg etc...
在 zip 中,我只想要檔案,而不是它們的關聯目錄。我該怎么辦?謝謝!
uj5u.com熱心網友回復:
我們可以使用該arcname引數來重命名 zip 檔案中的檔案。write我們可以通過簡單地將要添加的檔案的名稱傳遞給函式來洗掉目錄結構,這可以通過以下方式完成:
def return_zip():
dir_to_send = '/dir/to/the/files'
base_path = pathlib.Path(dir_to_send)
data = io.BytesIO()
with zipfile.ZipFile(data, mode='w') as z:
for f_name in base_path.iterdir():
z.write(f_name, arcname=f_name.name)
data.seek(0)
return send_file(data, mimetype='application/zip', as_attachment=True, attachment_filename='data.zip')
您可以在此處閱讀有關 zipfile 寫入功能的詳細資訊:https ://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.write
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/520052.html
下一篇:從多個類函式流式傳輸資料
