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
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))]
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:
['.bash_logout', '.bashrc', 'testfile.txt', '.profile', 'index.html']