Yenthe
Yenthe

Reputation: 2353

Get all filenames inside a directory on FTP [Python]

Today I ran into a big problem and because I'm fairly new with Python I'm really going to need to ask for help.

I've managed to connect to my FTP and login correctly.

ftp = ftplib.FTP('ftp.lala.com', 'username', 'pass')

As a second step I move into the dir that I'd like:

ftp.cwd("dirName")

But then I run stuck.. I now need to get all the filenames in a string / array / list / .. format to be able to use all those names. I've tried OS, glob, .. but this doesn't seem to work in any way. Any thoughts please? I would need to get every filename inside the dir that I want and also any directories/files within the wanted dir.

I somehow need to change this

for fileName in glob.glob("*.*"):
    self.out(fileName)

to go to the path ftp.lala.com/myDir/ and then get all the filenames out (also if there is a folder inside myDir)

Any suggestions or ideas are welcome! Thanks Yenthe

Upvotes: 5

Views: 14720

Answers (3)

user14875536
user14875536

Reputation:

from ftplib import FTP

ftp = FTP("hostname")
ftp.login("username", "password")
ftp.cwd("foldername")
files = ftp.nlst()
print(files)

Upvotes: 1

laoc81
laoc81

Reputation: 51

I get all path/files with this code:

import ftplib

server= ftplib.FTP_TLS('YOUR FTP ADRESS','USER','PASSWORD')
print("CONNECTED TO FTP")

files = server.nlst('your FTP folder path')
print(files)

Upvotes: 3

anon582847382
anon582847382

Reputation: 20351

How about:

contents = ftp.retrlines('LIST')  # List CWD contents securely.

Or:

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

contents is now a list of items within that directory that you can call.

Upvotes: 11

Related Questions