Using Python's ftplib to get a directory listing, portably Using Python's ftplib to get a directory listing, portably python python

Using Python's ftplib to get a directory listing, portably


Try using 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 as resp:    if str(resp) == "550 No files found":        print "No files in this directory"    else:        raisefor f in files:    print f


The reliable/standardized way to parse FTP directory listing is by using MLSD command, which by now should be supported by all recent/decent FTP servers.

import ftplibf = ftplib.FTP()f.connect("localhost")f.login()ls = []f.retrlines('MLSD', ls.append)for entry in ls:    print entry

The code above will print:

modify=20110723201710;perm=el;size=4096;type=dir;unique=807g4e5a5; testsmodify=20111206092323;perm=el;size=4096;type=dir;unique=807g1008e0; .xchat2modify=20111022125631;perm=el;size=4096;type=dir;unique=807g10001a; .gconfdmodify=20110808185618;perm=el;size=4096;type=dir;unique=807g160f9a; .skychart...

Starting from python 3.3, ftplib will provide a specific method to do this:


I found my way here while trying to get filenames, last modified stamps, file sizes etc and wanted to add my code. It only took a few minutes to write a loop to parse the ftp.dir(dir_list.append) making use of python std lib stuff like strip() (to clean up the line of text) and split() to create an array.

ftp = FTP('sick.domain.bro')ftp.login()ftp.cwd('path/to/data')dir_list = []ftp.dir(dir_list.append)# main thing is identifing which char marks start of good stuff# '-rw-r--r--   1 ppsrt    ppsrt      545498 Jul 23 12:07 FILENAME.FOO#                               ^  (that is line[29])for line in dir_list:   print line[29:].strip().split(' ') # got yerself an array there bud!   # EX ['545498', 'Jul', '23', '12:07', 'FILENAME.FOO']