Store filenames from a directory in an array
Sometimes you might need use a get a list of file names in an array without getting sub-diretory names. There are many ways to accomplish this task and I would like to discuss one of the ways we are using here at Walden Systems, because we believe this is the most straightforward method to get a list of files in a directory. We will be using os.path to do this.
Strategy to get a list of filenames : First, we need to iterate through the directory. Second, if it is a file, we add it to the array.
Here are actual code samples:
The first thing you need to do is import the os.path library with the following line :
import os.path
Then you need to do is import the isdir and join with the following line :
from os.path import isfile, join
Finally, you will add the filenames into an array only if it is a file not a directory :
file_array = [ f for f in os.listdir( SOME_DIRECTORY_PATH ) if isfile( join( SOME_DIRECTORY_PATH, f ) ) ]
So, this is how a final code :
1 import os.path 2 from os.path import isfile, join 3 4 file_array = [ f for f in os.listdir( SOME_DIRECTORY_PATH ) if isfile( join( SOME_DIRECTORY_PATH, f ) ) ]