This tutorial contains a sample Python script for listing all available files in a directory. This script will ignore all directories and subdirectories.
Advertisement
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.
1 2 | >>> 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.
1 2 3 4 5 6 7 | 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) |
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']