我有一个.zip文件,想知道其中的文件名.这是代码:
zip_path = glob.glob(path + '/*.zip')[0]
file = open(zip_path, 'r') # opens without error
if zipfile.is_zipfile(file):
print str(file) # prints to console
my_zipfile = zipfile.ZipFile(zip_path) # throws IOError
Run Code Online (Sandbox Code Playgroud)
这是追溯:
<open file u'/Users/me/Documents/project/uploads/assets/peter/offline_message/offline_imgs.zip', mode 'r' at 0x107b2a150>
Traceback (most recent call last):
File "/Users/me/Documents/project/admin_dev/proj_name/views.py", line 1680, in get_dps_app_builder_assets
link_to_assets_zip = zip_dps_app_builder_assets(server_url, app_slug, button_slugs)
File "/Users/me/Documents/project/admin_dev/proj_name/views.py", line 1724, in zip_dps_app_builder_assets
my_zipfile = zipfile.ZipFile(zip_path)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/zipfile.py", line 712, in __init__
self._GetContents()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/zipfile.py", line 746, in _GetContents
self._RealGetContents()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/zipfile.py", line 779, in _RealGetContents
fp.seek(self.start_dir, 0)
IOError: [Errno 22] Invalid argument
Run Code Online (Sandbox Code Playgroud)
我很困惑为什么会发生这种情况,因为文件显然在那里并且是一个有效的.zip文件.文档明确指出,您可以将其传递给文件的路径或类似文件的对象,在我的情况下,这两者都不起作用:
sta*_*345 -2
我无法解决这个问题,最终以完全不同的方式解决了这个问题。
编辑:在我使用的 Django 应用程序中,用户需要能够以 .zip 文件的形式上传资源,然后在具有不同结构的另一个 zip 中下载他们上传的所有内容(以及我们动态生成的其他内容)。因此,我想解压缩之前上传的文件并将该文件的内容压缩到另一个 zip 中,但由于错误而无法执行此操作。当用户请求下载时,我没有读取 zip 文件,而是从 Django InMemoryUploadedFile(我能够成功读取其内容)中解压缩它,并将解压缩的文件保留在文件系统上以供以后使用。zip 的内容只是两个较小的图像文件,因此提前解压缩 zip 以便稍后使用的解决方法对于我的目的来说效果很好。