使用Python动态压缩和ftp字符串

使用Python动态压缩和ftp字符串,python,ftp,zip,ftplib,in-memory,Python,Ftp,Zip,Ftplib,In Memory,我想压缩一个字符串(可能非常大)并通过FTP发送。 到目前为止,我正在使用ftplib和ziplib,但它们相处得不太好 ftp = FTP(self.host) ftp.login(user=self.username, passwd=self.password) ftp.cwd(self.remote_path) buf = io.BytesIO(str.encode("This string could be huge!!")) zip = ZipFile.ZipFile(buf, m

我想压缩一个字符串(可能非常大)并通过FTP发送。 到目前为止,我正在使用ftplib和ziplib,但它们相处得不太好

ftp = FTP(self.host)
ftp.login(user=self.username, passwd=self.password)
ftp.cwd(self.remote_path)

buf = io.BytesIO(str.encode("This string could be huge!!"))

zip = ZipFile.ZipFile(buf, mode='x')
# Either one of the two lines 
ftp.storbinary("STOR " + self.filename, buf) # Works perfectly!
ftp.storbinary("STOR " + self.filename, zip) # Doesnt Work

ftp.quit()
行不起作用时抛出以下错误

KeyError:“存档中没有名为8192的项”

我试图将文件压缩到bytesio,但没有成功

我需要在记忆中完成这一切。我不能先在服务器上写zip文件,然后再在ftp上写


另外,我需要通过纯FTP来完成,没有SFTP也没有SSH

我认为你把这个问题搞错了

ftp.storbinary
需要一个
bytes
对象,而不是
ZipFile
对象。您需要使用未压缩数据中的压缩数据创建
bytes
对象,并将其传递给
ftp.storbinary
。此外,您还必须为存档中的文件提供名称

此代码段从字符串创建这样的对象(独立示例)

现在根据您的上下文进行调整:

ftp = FTP(self.host)
ftp.login(user=self.username, passwd=self.password)
ftp.cwd(self.remote_path)

buf = str.encode("This string could be huge!!")
output_io = io.BytesIO()

zipfile_ob = zipfile.ZipFile(output_io,"w",zipfile.ZIP_DEFLATED)
zipfile_ob.writestr("your_data.txt",buf)
zipfile_ob.close()
output_io.seek(0)   # rewind the fake file
ftp.storbinary("STOR " + self.filename, output_io)

ftp.quit()
需要
seek
部分,否则您将在文件末尾传递
output\u io
类似文件的对象(您刚刚对其进行了写入,因此当前位置为:流结束)。使用
seek(0)
倒带类似文件的对象,以便从一开始就可以读取

请注意,对于一个文件,最好使用
Gzip
对象

ftp = FTP(self.host)
ftp.login(user=self.username, passwd=self.password)
ftp.cwd(self.remote_path)

buf = str.encode("This string could be huge!!")
output_io = io.BytesIO()

zipfile_ob = zipfile.ZipFile(output_io,"w",zipfile.ZIP_DEFLATED)
zipfile_ob.writestr("your_data.txt",buf)
zipfile_ob.close()
output_io.seek(0)   # rewind the fake file
ftp.storbinary("STOR " + self.filename, output_io)

ftp.quit()