+3 votes
in Programming Languages by (73.8k points)
I want to find all the files in a particular directory using python. The output should be a list containing all filenames. Could anyone please give me the simplest python code.

1 Answer

+1 vote
by (348k points)
selected by
 
Best answer

You need to use OS library of python to do this. Please see the following sample code:

import os

 filenames = next(os.walk(path_to_directory))[2]

Replace path_to_directory with your directory path. The output filenames will be a list with all files in that directory.

Example: 

>>> filenames = next(os.walk('/home/pkumar81/'))[2]
>>> filenames
['.bash_logout', '.bash_profile', '.bashrc', '.emacs', '.bash_history', '.lesshst'.......]

You can also use the glob module that provides the function glob() to list all the files in a directory.

import glob
filenames = glob.glob('*.*')
print(filenames)


...