简体   繁体   English

Python zipfile-IOError:[Errno 2]没有这样的文件或目录:zip_file

[英]Python zipfile - IOError: [Errno 2] No such file or directory : zip_file

pyMOTW pyMOTW

I need to create a ZIP file and save this file as binary in the database. 我需要创建一个ZIP文件并将该文件另存为二进制文件在数据库中。 I used reference from above website. 我使用了上述网站的参考。 My code is as below: 我的代码如下:

import time
import zipfile
import base64
zip_file = 'some_file_name.zip'
xml_file = 'xml_file.xml'
zf = zipfile.ZipFile(zip_file, mode='w',)
try:
   info = zipfile.ZipInfo(xml_file, 
                                   date_time=time.localtime(time.time()),
                                   )
   info.compress_type=zipfile.ZIP_DEFLATED
   info.comment='Remarks go here'
   info.create_system=0
   zf.writestr(info, "<Some XML string>")
finally:
   zf.close()
out = base64.encodestring(zf) # I need to convert zip into binary data in order to update this into database using ORM methods.

I don't need to read/write this zip file on File system. 我不需要在文件系统上读取/写入此zip文件。 I just need to create it programmatically and convert it into binary. 我只需要以编程方式创建它并将其转换为二进制。

I'm getting this error on the line : zf = zipfile.ZipFile(zip_file, mode='w',) Error traceback: 我在行上收到此错误:zf = zipfile.ZipFile(zip_file,mode ='w',)错误回溯:

File "/usr/lib/python2.7/zipfile.py", line 756, in __init__
   self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: u'some_file_name.zip'

Sorry for my bad indentation. 对不起,我缩进了。 Please help me out of this. 请帮助我。 Thanks in advance. 提前致谢。

You don't have the file some_file_name.zip yet, so it cannot find it. 您还没有some_file_name.zip文件,因此找不到它。 Instead, try using zip_file = StringIO.StringIO() and then save the filename later on. 而是尝试使用zip_file = StringIO.StringIO() ,然后再保存文件名。 I am not sure how to do that, because I am not sure what you want to do with the file. 我不确定该怎么做,因为我不确定您要对文件做什么。 But I guess there is a way to define the filename when you save it on disk or database. 但是我想当您将文件名保存在磁盘或数据库中时,有一种定义文件名的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM