[Tutor] Updating an FTP file

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 2 Mar 2001 13:48:26 -0800 (PST)


On Fri, 2 Mar 2001, Tim Johnson wrote:

> # I can then add the new line:
> lines.append("this is the new line")
> #here's where I 'hit the wall':
> # How do I 'write' the update list of line back to the
> # remote file. 

Hello!

It looks like we need to give a file-like object to either storbinary() or
storlines().  Since we're working with text, let's use storlines.

>From the documentation, storlines takes in a command, like "STOR
filename", and a file-like object.  The tricky thing we need is a
file-like object that has those changes that you've made before.  One easy
thing to do is to write a temporary file that reflects those changes,
upload that, and then erase the temporary file.

However, it sounds like you don't want to write an intermediate temporary
file, so let's try a different approach.  There's a module called
StringIO, which allows one to simulate a string as a file!  We could write
all our lines into a StringIO, and pass that along to storlines(); I think
that storlines() should be happy with that.

Let's see how StringIO works:

###
>>> from StringIO import StringIO
>>> myfile = StringIO()
>>> myfile.writelines(['this is a test', 'hello world',                        
...                    'does this work?'])
>>> myfile.seek(0)              ## Let's rewind the file back
>>> print myfile.read()
this is a testhello worlddoes this work?
>>> myfile.seek(0)
###

I have no idea if this will work with storlines() though, so try it out,
and tell us if you have any success with this.


For more details, take a look at:

    http://python.org/doc/current/lib/ftp-objects.html
    http://python.org/doc/current/lib/module-StringIO.html


Good luck!