mimicking a file in memory
Peter Otten
__peter__ at web.de
Wed Dec 12 14:14:28 EST 2007
mgierdal at gmail.com wrote:
> On Nov 20, 4:37 pm, Jarek Zgoda <jzg... at o2.usun.pl> wrote:
>
>> Try with StringIO/cStringIO, these modules are supposed to give you
>> in-memoryobjects compatible with file object interface.
>
> I found this solution not working.
> I had similar problem: I wanted to write some string into the in-
> memory file, then transfer it via ftp to some file and forget in-
> memory content.
>
> from ftplib import FTP
> ftp = FTP('ftp.server.org')
> ftp.login('ID','pswd')
> import StringIO
> filename = 'some_file.txt'
> command = 'STOR ' + filename
> outfile = StringIO.StringIO()
> outfile.write(some_string + '\n')
Try it again with
outfile.seek(0)
before the storlines() call.
> ftp.storlines(command, outfile)
> ftp.quit()
> outfile.close()
>
> The file shows up on the FTP server, but with ZERO length.
I believe you would see the same problem if outfile were a real file.
> I think the
> problem is that ftp.storelines attempts to use outfile's read()
> function, which is not present in StringIO objects (they use
> getvalue() instead). Quite an annoying inconsistency.
>>> "read" in dir(StringIO.StringIO())
True
A quick look into the source code can put an end to the rest of that
speculation:
def storlines(self, cmd, fp):
'''Store a file in line mode.'''
self.voidcmd('TYPE A')
conn = self.transfercmd(cmd)
while 1:
buf = fp.readline()
if not buf: break
if buf[-2:] != CRLF:
if buf[-1] in CRLF: buf = buf[:-1]
buf = buf + CRLF
conn.sendall(buf)
conn.close()
return self.voidresp()
storlines() will happily accept every object fp featuring a readline()
method.
> Any thoughts, please?
Keep the library docs under your pillow and the library source on your
screen :)
Peter
More information about the Python-list
mailing list