How To List All Files Of A Directory in Python

Are you looking for a method to list all the files in a directory? In this article, I will show you how you can list all files of a directory using Python quickly.

I will be using a list to populate all the filenames present in a directory. And append all the files found during the iteration of the directory using Python.

Using os.listdir Method present in OS Library

In Python, we have an OS library[1] that is used to interact with the Operating System. In this library, we have a method name listdir that is used to list all the directories and files present inside the input folder.

os.listdir() will return a list of all of the files and directories contained within a directory.

Using this method you can easily list down all the files present in the directory. Let us see that in the below working example code for Python.

#importing os library to talk with Operating System
import os

#Print all the Subfolder and Files present in Directory
print(os.listdir('C:\Python310\Tools'))

Output:

['demo', 'i18n', 'pynche', 'scripts', 'StripViewer.py', 'Switchboard.py', 'TextViewer.py']

As you can see using os.listdir creates the list of all the directories and files present inside the Tools folder. If you want to only list files present in the directory and do not want to list the subfolders then follow the below-mentioned method.

Using os.path Method to List only Files present inside the Directory

If you only want files, you could either use the os.path function to narrow this down. As you can use this method to only get the list of files under the directory. Let us see that in below example code.

#importing os library to talk with Operating System
#importing listdir and os.path
import os
from os import listdir
from os.path import isfile, join

#Initializing the Input Directory 
directoryPath = "C:\Python310\Tools"

#Creating a List of File including the Path.
onlyFilesList = [os.path.join(directoryPath, filename) for filename in os.listdir(directoryPath) if 
os.path.isfile(os.path.join(directoryPath, filename))]

#Printing the List of Files
print(onlyFilesList)

#Creating the List without Path and only Filenames
onlyFilesList = [os.path.join(filename) for filename in os.listdir(directoryPath) if 
os.path.isfile(os.path.join(directoryPath, filename))]

#Printing the List of Files
print(onlyFilesList)

Output:

['C:\\Python310\\Tools\\StripViewer.py', 'C:\\Python310\\Tools\\Switchboard.py', 'C:\\Python310\\Tools\\TextViewer.py']
['StripViewer.py', 'Switchboard.py', 'TextViewer.py']

As you can see using the above code, I was able to print the full file path along with their names and then I modified the list to print only the file names present inside the input directory.

Using os.walk To List All Files of a Directory

There is another method in os library namely walk. This method can also be used to list down all the files present in the given directory.

Each directory os.walk() traverses will return a list of files and directories. It is possible to break if you only want the top directory or files.

#importing os library to talk with Operating System
#importing listdir and os.path
from os import walk

#Initializing List for FileNames to be saved
fileNameList = []

#Initializing the Input Directory
directoryToSearch = "C:\Python310\Tools"

#Looping through all the files and Sub Directories using this Loop
for (dirpath, dirnames, filenames) in walk(directoryToSearch):
    fileNameList.extend(filenames)
    #using Break to End the Search once Filenames are 
    # looped into current library
    break

print(fileNameList)

Output:

['StripViewer.py', 'Switchboard.py', 'TextViewer.py']
How To List All Files Of A Directory in Python

As you can see in the above code, I have used the break to end the loop once it completes looping for all the files present in the current directory. If you will not use the break in the above code then you will get a list of all the files present inside the subdirectories as well.

List all the files present in directory and sub directory

As already discussed above, all you need to do is remove the break statement from the above code and execute it.

#importing os library to talk with Operating System
#importing listdir and os.path
from os import walk

#Initializing List for FileNames to be saved
fileNameList = []

#Initializing the Input Directory
directoryToSearch = "C:\Python310\Tools"

#Looping through all the files and Sub Directories using this Loop
for (dirpath, dirnames, filenames) in walk(directoryToSearch):
    fileNameList.extend(filenames)

print(fileNameList)

Output:

['StripViewer.py', 'Switchboard.py', 'TextViewer.py', 'beer.py', 'eiffel.py', 'hanoi.py', 'life.py', 'markov.py', 'mcast.py', 'queens.py', 'redemo.py', 'rpython.py', 'rpythond.py', 'sortvisu.py', 'spreadsheet.py', 'vector.py', 'makelocalealias.py', 'msgfmt.py', 'pygettext.py', 'ChipViewer.py', 'ColorDB.py', 'DetailsViewer.py', 'html40colors.txt', 'ListViewer.py', 'Main.py', 'namedcolors.txt', 'pyColorChooser.py', 'pynche.pyw', 'PyncheWidget.py', 'StripViewer.py', 'Switchboard.py', 'TextViewer.py', 'TypeinViewer.py', 'webcolors.txt', 'websafe.txt', '__init__.py', 'rgb.txt', 'xlicense.txt', '2to3.py', 'abitype.py', 'analyze_dxp.py', 'byext.py', 'byteyears.py', 'checkpip.py', 'cleanfuture.py', 'combinerefs.py', 'copytime.py', 'crlf.py', 'db2pickle.py', 'diff.py', 'dutree.py', 'eptags.py', 'find-uname.py', 'finddiv.py', 'findlinksto.py', 'findnocoding.py', 'find_recursionlimit.py', 'fixcid.py', 'fixdiv.py', 'fixheader.py', 'fixnotice.py', 'fixps.py', 'generate_opcode_h.py', 'generate_stdlib_module_names.py', 'generate_token.py', 'get-remote-certificate.py', 'google.py', 'gprof2html.py', 'highlight.py', 'ifdef.py', 'import_diagnostics.py', 'lfcr.py', 'linktree.py', 'lll.py', 'mailerdaemon.py', 'make_ctype.py', 'md5sum.py', 'mkreal.py', 'ndiff.py', 'nm2def.py', 'objgraph.py', 'parseentities.py', 'parse_html5_entities.py', 'patchcheck.py', 'pathfix.py', 'pdeps.py', 'pep384_macrocheck.py', 'pickle2db.py', 'pindent.py', 'ptags.py', 'pydoc3.py', 'pysource.py', 'reindent-rst.py', 'reindent.py', 'rgrep.py', 'run_tests.py', 'serve.py', 'smelly.py', 'stable_abi.py', 'suff.py', 
'texi2html.py', 'untabify.py', 'update_file.py', 'var_access_benchmark.py', 'which.py', 'win_add2path.py']

Using glob Method to List All Files with Pattern Matching Feature

You want to list all the files present inside the directory that matches your given pattern. For example, if you want to list all the files that is having only extension as *.txt then you can use the glob method.

Note that glob is the different library that needs to be imported and here os library is not required to be imported as glob will handle everything. Let us see in the below example code for its usage.

#importing glob for Pattern Matching
import glob

#Initializing the Path
directoryToSearchFiles = "C:\Python310\Tools"

fileInsideTheCurrentDirectory = glob.glob(directoryToSearchFiles + "/*.py")

# All files ending with .py
print(fileInsideTheCurrentDirectory) 

filesInsideSubFolderAsWell = glob.glob(directoryToSearchFiles + "/*/*.py")

# All files ending with .py with depth of 2 folder
#print(filesInsideSubFolderAsWell)

Output:

['C:\\Python310\\Tools\\StripViewer.py', 'C:\\Python310\\Tools\\Switchboard.py', 'C:\\Python310\\Tools\\TextViewer.py']

Wrap Up

That is all for this post on how to list all files of a directory using python. I hope I was able to give you a lot of options to choose from. If you have any better solution to the above problem then please provide that in the comments section.

Then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. How To Remove A Specific item From An Array
  2. How To Convert a Char to String in C++ Quickly
  3. How to Remove Last Element From List In Python
  4. Equivalent to “source” in OpenBSD? Python Linux/Unix
  5. Trapping Rain Water Problem Python JAVA C++ Solution
  6. How to Write Enhanced For Loop in Java With Examples

Leave a Comment