使用Python即时压缩和ftp字符串

使用Python即时压缩和ftp字符串

本文介绍了使用Python即时压缩和ftp字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to zip a string(could be very big) and send it through FTP.So far I am using ftplib and ziplib, but they are not getting along too well.

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()

行不起作用会引发以下错误.

The line that doesn't work throws me the following error.

我尝试将文件压缩到bytesio,但未成功.

I tried to zip the file to bytesio without success.

我需要在内存中完成所有这些操作.我无法先将zip文件写入服务器,然后再写入ftp.

I need to do this all in memory. I cant write the zip file on the server first and then ftp.

此外,我需要通过纯FTP,而不是SFTP或SSH来完成此操作.

Also, I need to do it through pure FTP, no SFTP nor SSH.

推荐答案

我认为您正以错误的方式解决问题.

I think you're taking the problem the wrong way round.

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

ftp.storbinary needs a bytes object, not a ZipFile object. You need to create bytes object with compressed data out of your uncompressed data, and pass that to ftp.storbinary. Plus you have to provide a name for the file in the archive.

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

this snippet creates such an object from a string (standalone example)

import zipfile,io

output_io = io.BytesIO()

zipfile_ob = zipfile.ZipFile(output_io,"w",zipfile.ZIP_DEFLATED)
zipfile_ob.writestr("your_data.txt",b"big string to be compressed"*20)
zipfile_ob.close()

现在已适应您的情况:

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_io的文件对象(您刚刚写入它,因此当前位置是:流的末尾).使用seek(0)可以倒回文件状对象,以便可以从头开始读取.

The seek part is needed else you're passing the output_io file-like object while at the end of the file (you just wrote to it so current position is: end of stream). Using seek(0) rewinds the file-like object so it can be read from the start.

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

note that for only one file, it may be better to use a Gzip object.

这篇关于使用Python即时压缩和ftp字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 10:41