我可以使用Python将内存中的对象上载到FTP吗?
以下是我现在正在做的:我可以使用Python将内存中的对象上载到FTP吗?,python,object,ftp,upload,ftplib,Python,Object,Ftp,Upload,Ftplib,以下是我现在正在做的: 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.re
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')
将文件写入磁盘,然后立即删除它们似乎是系统上应该避免的额外工作。我可以使用Python将内存中的对象上载到FTP吗?因为,文件对象(f
在代码中)只需要支持.read(blocksize)
调用即可使用storbinary
。当遇到这样的问题时,我会转到源代码,在本例中是lib/python2.6/ftplib.py:
import urllib
import ftplib
ftp = ftplib.FTP(...)
f = urllib.urlopen('http://localhost/image.jpg')
ftp.storbinary('STOR image.jpg', f)
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()
正如所评论的,它只需要一个,实际上它甚至不是特别像文件,它只需要read(n)
。提供此类“内存文件”服务。因为,文件对象(f
在代码中)只需要支持.read(blocksize)
调用即可使用storbinary
。当遇到这样的问题时,我会转到源代码,在本例中是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()
正如所评论的,它只需要一个,实际上它甚至不是特别像文件,它只需要read(n)
。提供此类“内存文件”服务。您可以使用内存中的任何内容,如:
它在二进制模式下工作,具有:
以及在ascii/文本模式下使用:
有关更高级的示例,请参见:
有关更高级的示例,请参见:
f = BytesIO(b"the contents")
ftp.storbinary("STOR /path/file.txt", f)
f = BytesIO(b"the contents")
ftp.storlines("STOR /path/file.txt", f)