ftp recursively

Arnaud Delobelle arnodel at googlemail.com
Tue Mar 18 18:12:16 EDT 2008



Jeff Schwab wrote:
> I need to move a directory tree (~9GB) from one machine to another on
> the same LAN.  What's the best (briefest and most portable) way to do
> this in Python?
>
> I see that urllib has some support for getting files by FTP, but that it
> has some trouble distinguishing files from directories.
>
>      http://docs.python.org/lib/module-urllib.html
>
>      "The code handling the FTP protocol cannot differentiate
>       between a file and a directory."
>
> I tried it anyway, but got an authentication problem.  I don't see a
> "how to log into the FTP server" section on docs.python.org.  Is there a
> tutorial I should read?
>
> I am particularly looking for a quick, "good enough" solution that I can
> use this afternoon.  Thanks in advance to any kind-hearted soul who
> chooses to help me out.

Have you tried ftplib? (http://docs.python.org/lib/module-ftplib.html)
Here is an example of how to use it to differentiate between files and
directories (untested).

conn = ftplib.FTP('host', 'user', 'password')

def callback(line):
    name = line.rpartition(' ')[-1] # assumes no whitespace in
filenames
    if line[0] == 'd':
        #filename is a directory
        print 'directory', name
    else:
        print 'file', name

#This will print all files in cwd prefixed by 'directory' or 'file'
#You can change callback to retrieve files and explore
#directories recursively
conn.dir(callback)

HTH

--
Arnaud




More information about the Python-list mailing list