views:

42

answers:

1

I'd like to use ftplib to upload program-generated data as lists. The nearest method I can see for doing this is ftp.storlines, but this requires a file object with a readlines() method.

Obviously I could create a file, but this seems like overkill as the data isn't persistent.

Is there anything that could do this?:

session = ftp.new(...)
upload = convertListToFileObject(mylist)
session.storlines("STOR SOMETHING",upload)
session.quit
+3  A: 

You could always use StringIO (documentation), it is a memory buffer that is a file-like object.

from io import StringIO    # version < 2.6: from StringIO import StringIO

buffer = StringIO()
buffer.writelines(mylist)
buffer.seek(0)

session.storlines("...", buffer)

Note that the writelines method does not add line separators. So you need to make sure that each string in mylist ends with a \n. If the items in mylist do not end with a \n, you can do:

buffer.writelines(line + '\n' for line in mylist)
codeape
That's it! Of course. I'm getting forgetful in my old age.
Brent.Longborough
Note you would probably prefer the `cStringIO` module to the `StringIO` module (if you weren't using the `io` module).
Mike Graham