Get all filenames inside a directory on FTP [Python]
Asked Answered
M

3

5

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

Merta answered 10/3, 2014 at 15:42 Comment(0)
D
11

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.

Depose answered 10/3, 2014 at 15:53 Comment(3)
Due to the framework and platform that I use I can't use this one sadly. For 99% of the people this would in fact be good yes, but I need another way! Sorry I forgot to mention that.Merta
AWESOME! That in fact is a fix :) Now, would you also know a way to get all filenames if there are files inside a directory where is another directory? So Dir to search : file.css, file.html, file.txt, directory How can I get the files within the directory that is inside the dir I search for? By the way, awesome programming knowledge for your age.Merta
Fair enough! You've solved the main problem so I've accepted the answer. Thank you!Merta
H
3

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)
Hendecagon answered 19/2, 2021 at 0:55 Comment(0)
T
1
from ftplib import FTP

ftp = FTP("hostname")
ftp.login("username", "password")
ftp.cwd("foldername")
files = ftp.nlst()
print(files)
Trapeze answered 20/6, 2021 at 6:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.