How to List All files in a Directory using Python

Channel: Linux
Abstract: join dirName = '/home/rahul'fileNames = [f for f in listdir(dirName) if isfile(join(dirNamejoin dirName = '/home/rahul' fileNames = [f for f in listdi

This tutorial contains a sample Python script for listing all available files in a directory. This script will ignore all directories and subdirectories.

The Python listdir() function available under os package is used to listing all content of a directory. So you can simply print the results of the listdir() function. This will show files as well as directories. This function accepts an argument as a directory location.

>>> from os import listdir >>> listdir('/home/rahul')12>>> from os import listdir>>> listdir('/home/rahul')

Here our requirement is to list only files (not directories). So program needs to loop through the array resulted by listdir() and print only files ignoring rest.

from os import listdir from os.path import isfile, join dirName = '/home/rahul' fileNames = [f for f in listdir(dirName) if isfile(join(dirName, f))] print (fileNames)1234567from os import listdirfrom os.path import isfile, join dirName = '/home/rahul'fileNames = [f for f in listdir(dirName) if isfile(join(dirName, f))] print (fileNames)

Save the above script in a file (eg: myScript.py), Then execute this Python script on command line. You will see the results like below:

python myScript.py

Output:

['.bash_logout', '.bashrc', 'testfile.txt', '.profile', 'index.html']

Ref From: tecadmin

Related articles