問(wèn)題描述
這是我現(xiàn)在正在做的事情:
Here's what I'm doing now:
mysock = urllib.urlopen('http://localhost/image.jpg')
fileToSave = mysock.read()
oFile = open(r"C:image.jpg",'wb')
oFile.write(fileToSave)
oFile.close
f=file('image.jpg','rb')
ftp.storbinary('STOR '+os.path.basename('image.jpg'),f)
os.remove('image.jpg')
將文件寫(xiě)入磁盤(pán)然后立即刪除它們似乎是系統(tǒng)上應(yīng)該避免的額外工作.我可以使用 Python 將內(nèi)存中的對(duì)象上傳到 FTP 嗎?
Writing files to disk and then imediately deleting them seems like extra work on the system that should be avoided. Can I upload an object in memory to FTP using Python?
推薦答案
因?yàn)?duck-typing,文件對(duì)象(代碼中的f
)只需要支持.read(blocksize)
調(diào)用就可以使用storbinary
.當(dāng)遇到這樣的問(wèn)題時(shí),我會(huì)去源頭,在本例中是 lib/python2.6/ftplib.py:
Because of duck-typing, the file object (f
in your code) only needs to support the .read(blocksize)
call to work with storbinary
. When faced with questions like this, I go to the source, in this case lib/python2.6/ftplib.py:
def storbinary(self, cmd, fp, blocksize=8192, callback=None):
"""Store a file in binary mode. A new port is created for you.
Args:
cmd: A STOR command.
fp: A file-like object with a read(num_bytes) method.
blocksize: The maximum data size to read from fp and send over
the connection at once. [default: 8192]
callback: An optional single parameter callable that is called on
on each block of data after it is sent. [default: None]
Returns:
The response code.
"""
self.voidcmd('TYPE I')
conn = self.transfercmd(cmd)
while 1:
buf = fp.read(blocksize)
if not buf: break
conn.sendall(buf)
if callback: callback(buf)
conn.close()
return self.voidresp()
正如評(píng)論,它只需要一個(gè)類文件對(duì)象,實(shí)際上它甚至不是特別像文件,它只需要 read(n)
.StringIO 提供了這樣的內(nèi)存文件"服務(wù).
As commented, it only wants a file-like object, indeed it not even be particularly file-like, it just needs read(n)
. StringIO provides such "memory file" services.
這篇關(guān)于我可以使用 Python 將內(nèi)存中的對(duì)象上傳到 FTP 嗎?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!