Marius Pfeffer
Marius Pfeffer

Reputation: 41

python3 ftplib: check if dir exists via mlsd()

I'm working with Python3 and ftplib.

I need to check if a directory on the ftp server exists. (if not, I can create it, than cwd into it, if it already exists i will directly cwd into it).

I've seen the method from Marek Marecki here: How to make Python check if ftp directory exists?

if 'foo' in [name for name, data in list(remote.mlsd())]:

Problem being this will also trigger on files named 'foo'.

Is there a Pythonic way doing this (explicitly with mlsd()) ? nlst() is deprecated

Thanks a lot!

Upvotes: 1

Views: 5438

Answers (2)

Marius Pfeffer
Marius Pfeffer

Reputation: 41

Also thanks to @arnial

I cam up with following: (mlsd or nslt)

use_mlsd = 1
if(use_mlsd):
  # if ftp server supports mlsd, use it, nlst is maked as deprecated in ftplib
  # check if remotefoldername exists
  remotefoldername_exists = 0
  for name, facts in f.mlsd(".",["type"]):
    if facts["type"] == "dir" and name == "remote_ftp":
      print("isdir: "+ name)
      remotefoldername_exists = 1
      break
  if(remotefoldername_exists == 0)
    ftp.mkd(remotefoldername)
    logging.debug("folder does not exitst, ftp.mkd: " + remotefoldername)
  else:
    logging.debug("folder did exist: " + remotefoldername)

else:
    # nlst legacy support for ftp servers that do not support mlsd e.g. vsftp
    items = []
    ftp.retrlines('LIST', items.append ) 
    items = map( str.split, items )
    dirlist = [ item.pop() for item in items if item[0][0] == 'd' ]
    #print( "directrys", directorys )
    #print( 'remote_ftp' in directorys )
    if not (remotefoldername in dirlist):
      ftp.mkd(remotefoldername)
      logging.debug("folder does not exitst, ftp.mkd: " + remotefoldername)
    else:
      logging.debug("folder did exist: " + remotefoldername)

Upvotes: 1

Arnial
Arnial

Reputation: 1441

I don't have any server that support MLSD command, so i not sure how do this with mlsd. But this code should work even without MLSD support.

    items = []
    ftp.retrlines('LIST', items.append ) 
    items = map( str.split, items )
    directorys = [ item.pop() for item in items if item[0][0] == 'd' ]
    print( "directrys", directorys )
    print( 'foo' in directorys )

Upvotes: 0

Related Questions