How to check if folder exist inside a directory if not create it using python

mongotop picture mongotop · Jan 14, 2014 · Viewed 12.2k times · Source

I use the below python script to check if a file exist on the root of my ftp server.

from ftplib import FTP 
ftp = FTP('ftp.hostname.com')
ftp.login('login', 'password')

folderName = 'foldername'

if folderName in ftp.nlst() :
    print 'YES'
else : print 'NO'

How can I modify the above script to look inside a specific folder instead of the root directory?

For example, I want to see if a folder name called foo exists inside the www directory.

The goal of my question, is to see if the folder foo exists inside the www directory, if so print cool! if not create a folder called foo inside www.

Answer

wtayyeb picture wtayyeb · Apr 28, 2014
from ftplib import FTP 
ftp = FTP('ftp.hostname.com')
ftp.login('login', 'password')
where      = 'www'
folderName = 'foldername'

if folderName in ftp.nlst(where) :
    print 'YES'
else :
    print 'NO'

Just send the directory you want to see in as first argument of ftp.nlst()