views:

4329

answers:

2

You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is:

# File: ftplib-example-1.py

import ftplib

ftp = ftplib.FTP("www.python.org")
ftp.login("anonymous", "ftplib-example-1")

data = []

ftp.dir(data.append)

ftp.quit()

for line in data:
    print "-", line

Which yields:

$ python ftplib-example-1.py
- total 34
- drwxrwxr-x  11 root     4127         512 Sep 14 14:18 .
- drwxrwxr-x  11 root     4127         512 Sep 14 14:18 ..
- drwxrwxr-x   2 root     4127         512 Sep 13 15:18 RCS
- lrwxrwxrwx   1 root     bin           11 Jun 29 14:34 README -> welcome.msg
- drwxr-xr-x   3 root     wheel        512 May 19  1998 bin
- drwxr-sr-x   3 root     1400         512 Jun  9  1997 dev
- drwxrwxr--   2 root     4127         512 Feb  8  1998 dup
- drwxr-xr-x   3 root     wheel        512 May 19  1998 etc
...

I guess the idea is to parse the results to get the directory listing. However this listing is directly dependent on the FTP server's way of formatting the list. It would be very messy to write code for this having to anticipate all the different ways FTP servers might format this list.

Is there a portable way to get an array filled with the directory listing?

(The array should only have the folder names.)

+6  A: 

Try ftp.nlst(dir).

however note that if the folder is empty, it might throw an error:

files = []

try:
 files = ftp.nlst()
except ftplib.error_perm, resp:
 if str(resp) == "550 No files found":
  print "no files in this directory"
 else:
  raise

for f in files
 print f
William Keller
Oh, nicely spotted on the 550! Upvoted. :)
Garth T Kidd
+2  A: 

There's no standard for the layout of the LIST response. You'd have to write code to handle the most popular layouts. I'd start with Linux ls and Windows Server DIR formats. There's a lot of variety out there, though.

Fall back to the nlst method (returning the result of the NLST command) if you can't parse the longer list. For bonus points, cheat: perhaps the longest number in the line containing a known file name is its length.

Garth T Kidd
Never ever you should assume that. Guessing always leads to abscure bugs when you least expect them
iElectric
Quite true, hence my many unit tests and integration tests. :) If they need the length, though, it's either: hope the format matches one of those they've tested against; break; or try to figure out where to find the length. None of the options are ideal.
Garth T Kidd