[英]How to read contents of zip file in memory on a file upload in python?
我有一個用戶上傳文件時收到的zip
文件。 zip
本質上包含一個json
文件,我想讀取和處理它,而不必先創建zip
文件,然后解壓縮它,然后讀取內部文件的內容。
目前我只有更長的過程,如下所示
import json
import zipfile
@csrf_exempt
def get_zip(request):
try:
if request.method == "POST":
try:
client_file = request.FILES['file']
file_path = "/some/path/"
# first dump the zip file to a directory
with open(file_path + '%s' % client_file.name, 'wb+') as dest:
for chunk in client_file.chunks():
dest.write(chunk)
# unzip the zip file to the same directory
with zipfile.ZipFile(file_path + client_file.name, 'r') as zip_ref:
zip_ref.extractall(file_path)
# at this point we get a json file from the zip say `test.json`
# read the json file content
with open(file_path + "test.json", "r") as fo:
json_content = json.load(fo)
doSomething(json_content)
return HttpResponse(0)
except Exception as e:
return HttpResponse(1)
如您所見,這涉及最終將zip
文件中的內容放入內存的 3 個步驟。 我想要的是獲取zip
文件的內容並直接加載到內存中。
我確實在堆棧溢出中發現了一些類似的問題,例如https://stackoverflow.com/a/2463819 。 但是我不確定在什么時候調用帖子中提到的這個操作
我怎樣才能做到這一點?
注意:我在后端使用 django。 zip 中總會有一個 json 文件。
zipfile.ZipFile()
的第一個參數可以是文件對象而不是路徑名。 我認為 Django UploadedFile
對象支持這種用法,因此您可以直接從中讀取,而不必復制到文件中。
您還可以直接從 zip 存檔打開文件,而不是將其解壓縮到文件中。
import json
import zipfile
@csrf_exempt
def get_zip(request):
try:
if request.method == "POST":
try:
client_file = request.FILES['file']
# unzip the zip file to the same directory
with zipfile.ZipFile(client_file, 'r') as zip_ref:
first = zip_ref.infolist()[0]
with zip_ref.open(first, "r") as fo:
json_content = json.load(fo)
doSomething(json_content)
return HttpResponse(0)
except Exception as e:
return HttpResponse(1)
據我了解,@jason在這里想說的是首先打開一個 zipFile,就像你在這里with zipfile.ZipFile(file_path + client_file.name, 'r') as zip_ref:
。
class zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])
Open a ZIP file, where file can be either a path to a file (a string) or a file-like object.
然后使用BytesIO讀取一個類文件對象的字節。 但是從上面你是在r
模式而不是rb
模式下閱讀。 所以改成如下。
with open(filename, 'rb') as file_data:
bytes_content = file_data.read()
file_like_object = io.BytesIO(bytes_content)
zipfile_ob = zipfile.ZipFile(file_like_object)
現在zipfile_ob
可以從內存中訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.