Is there a simple way to make lists behave as files (with ftplib)
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() metho开发者_开发技巧d.
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
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)
精彩评论