The mlsd() method of FTP class in Python

The method mlsd() returns the contents of a directory in a standard format for the consumption of computer programs. It implements the ftp command MLSD. The example python program gets the directory listing for the current working directory, prints the name of each element and the facts dictionary for each element.

Ftp Updated 15 Oct 2019 1 min read

Method Name

mlsd

Method Signature

mlsd(path=””, facts=[])

Return Value

A generator that yields a tuple, containing name of the directory elements and a dictionary containing details of the directory element.

Overview

  • The method mlsd() implements the FTP command MLSD.
  • While the methods dir() and mlsd() both lists contents of a directory, mlsd() provides it in a standard format so as to be easy for processing by computer programs.
  • Unlike the dir() method mlsd() does not work on a file name.

Example

python
# Example Python program that uses FTP command MLSD

from ftplib import FTP

# Create an FTP instance and connect to the FTP server

ftpObject = FTP(host="agreatftpserver.com");

# Login to the FTP server

ftpObject.login(user="someuser@agreatftpserver.com", passwd="aadghbP654fDf17HGvD");

# Issue MLSD to get detailed listing of directory(pwd) contents

for name, facts in ftpObject.mlsd():

    print(name);

    print("////");

    print(facts);

Output

Output
python3.7 mlsd.py

.

////

{'type': 'cdir', 'sizd': '69632', 'modify': '20191015110043', 'unix.mode': '0700', 'unix.uid': '813', 'unix.gid': '593', 'unique': '700ga214b2'}

..

////

{'type': 'pdir', 'sizd': '69632', 'modify': '20191015110043', 'unix.mode': '0700', 'unix.uid': '813', 'unix.gid': '593', 'unique': '700ga214b2'}

LogFile.txt

////

{'type': 'file', 'size': '221680', 'modify': '20191015110341', 'unix.mode': '0644', 'unix.uid': '813', 'unix.gid': '593', 'unique': '700ga2009e'}