Python - Directory Listing


Advertisements

Python can be used to get the list of content from a directory. We can make program to list the content of directory which is in the same machine where python is running. We can also login to the remote system and list the content from the remote directory.

Listing Local Directory

In the below example we use the listdir() method to get the content of the current directory. To also indicate the type of the content like file or directory, we use more functions to evaluate the nature of the content.

for  name in os.listdir('.'):
    if os.path.isfile(name): print 'file: ', name
    elif os.path.isdir(name): print 'dir: ', name
    elif os.path.islink(name): print 'link: ', name
    else: print 'unknown', name

When we run the above program, we get the following output −

file: abcl.htm
dir: allbooks
link: ulink

Please note the content above is specific to the system where the python program was run. The result will vary depending on the system and its content.

Listing Remote Directory

We can list the content of the remote directory by using ftp to access the remote system. Once the connection is established we can use commands that will list the directory contents in a way similar to the listing of local directories.

from ftplib import FTP
def main():
    ftp = FTP('ftp.ibiblio.org')
    ftp.login()
    ftp.cwd('pub/academic/biology/') # change to some other subject
    entries = ftp.nlst()
    ftp.quit()

    print(len(entries), "entries:")
    for entry in sorted(entries):
        print(entry)

if __name__ == '__main__':
    main()

When we run the above program, we get the following output −

(6, 'entries:')
INDEX
README
acedb
dna-mutations
ecology+evolution
molbio
Advertisements