Spot any errors? let me know, but Unleash your pedant politely please.

Sunday, 30 January 2011

Python FTW: Clearing an FTP folder.

I'm doing some testing that involves kicking off a lot of concurrent processes. Some of these write files to an FTP server. I don't need those files once I've checked that they exist, but FTP doesn't allow deletion of multiple files (AFAIK). The first time we cleared the server, we took a directory listing and wrote an FTP script from that. It worked well enough, but we'd need to write that script each time.

So a little play with Python gave me this...


from ftplib import FTP

def clearFTPDirectory(address,
username,
directory):

server=FTP(address)
server.login(username)
server.cwd(directory)

directory=[]
server.dir(directory.append)

# list comprehension, baby!
filenames=[entry.split(':')[-1][3:] for entry in directory]

for filename in filenames:
try:
server.delete(filename)
print 'Deleted:%s'%filename
except:
print ('failed to delete "%s"'%filename)

server.quit()
…it should save a fair few cumulative hours, but more importantly, it'll save a fair few hours of tedium.

The bit that tripped me up for a little while was server.dir(directory.append) which takes the append function as a parameter. Makes perfect sense now.

Note: if you use this, you may need to check the format of the strings returned by dir(), and adjust the line that extracts the filename.

No comments:

Post a Comment