7

How exactly would you create a list of the entries in an FTP directory?

This is my code so far:

import ftplib

files = []

my_ftp = ftplib.FTP(HOST)
my_ftp.login(USERNAME,PASSWORD)

line = my_ftp.retrlines("NLST",files.append(line))
my_ftp.quit()

The error says that the variable line is being used before it is defined.

Vishesh Shrivastav
  • 2,079
  • 2
  • 16
  • 34
Abram I
  • 185
  • 2
  • 7

2 Answers2

10

You probably just want to use nlst:

>>> my_ftp.nlst()
['pub', 'etc', 'ports']
Mattie
  • 20,280
  • 7
  • 36
  • 54
5

A little change to the callback argument and the following should work

line = my_ftp.retrlines("NLST",files.append)
Milo Wielondek
  • 4,164
  • 3
  • 33
  • 45
  • Documentation says `retrlines` will call `print_line` if you don't specify `callback`. That won't work. – Mattie Apr 01 '12 at 23:47
  • Ahh, `files.append` is even better than `lambda`. Why didn't I think of that? :-) – Mattie Apr 01 '12 at 23:52
  • This is probably not worth doing with `NLST`, because as zigg's answer points out, just `.nlst()` returns a list. This is still worth doing if you want to `.retrlines('LIST -t')` or something, though. – Jan Kyu Peblik Sep 05 '18 at 17:10