Python Forum
ftplib os.listdir function
Thread Rating:
  • 2 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
ftplib os.listdir function
#1
Hello everyone,

I'm looking for a method like os.listdir(), but in the ftplib, within a ftp server. I want to list every dir on the ftp server and it's contents, if there's a dir inside dir list its contents as well. Here's where I have so far

import ftplib
ftpinstance = ftplib.FTP('ftp server','username','password') 
dirk = ''
listofitems = ''
def list_item(dirk,listofitems):
    if listofitems == '': 
        listofitems = []
        try:
            ftpinstance.retrlines('NLST',listofitems.append) #GETS files' names (dirs or files) of the current dir 
            mwd = ftpinstance.pwd()
            for item in listofitems:
                ftpinstance.cwd(mwd+'/'+item+'/')
                listofitems2 = []
                ftpinstance.retrlines('NLST',listofitems2.append) #IF not a dir here, error occurs prints it's a file.
                print ('Folder found:',item)
                cwd = ftpinstance.pwd()
                list_item(cwd,listofitems2)
        except Exception as e:
            print (e)
            print ('File Found:',item)
    else:
        mwd = ftpinstance.pwd()
        for item in listofitems:
            try:
                ftpinstance.cwd(mwd+'/'+item+'/')
                listofitems2 = []
                ftpinstance.retrlines('NLST',listofitems2.append)
                print ('Folder found:',item)
                cwd = ftpinstance.pwd()
                list_item(cwd,listofitems2)            
            except Exception as e:
                print (e)
                print ('File Found:',item)

list_item(dirk,listofitems)
I can't print out the content of several dirs (for 4 dirs inside) only of the first two(with this code) If you don't understand something in the code do not hesitate to ask me. The while point is really to make a similar os.list() command to FTP, I did not find one in the documentation of the library, plus I had a look at the os lib code, but I did not find the os.list dir command code.

I'm using python3.5 in Linux. Thank you in advance
Reply


Messages In This Thread
ftplib os.listdir function - by peterkl - Nov-30-2016, 08:55 PM
RE: ftplib os.listdir function - by heiner55 - Jun-07-2019, 08:21 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  ftplib and pyftpdlib : REST (restart) command not working as expected when uploading darellon 3 5,225 Mar-05-2017, 01:11 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020