How to list all files inside a directory with Python

Being a Python geek, most of the time it happens that I make use of my knowledge to write simple scripts which automate repetitive tasks in my operating system. Rich in features, Python offers many utilities which help the Python coder to interact with the functionalities of the operating system. Based on my personal experience with the Python computer programming language, one of the modules which has packed the utilities that can interact with the operating system, is the os module.

The Python coder can easily make use of the utilities included in the os module by importing them in their application through the Python import statements. Through this tutorial, is going to teach the beginner of the Python computer programming language, how they can make use of the os.listdir utility to list files inside their directories being found in the file system.

Before one can make use of any Python utility included in the module, they have to import it first. The following piece of Python code, imports the listdir utility from the builtin os module.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

from os import listdir

According to the official Python documentation, the listdir utility, part of the builtin os module, needs the path of the directory which the user wants to list the files for.

I am going to list all the files inside the directory called EngineeringStudent, found in the Desktop folder of my Mac OS X machine. First, I need to declare the absolute path of the directory by following the syntax shown below.

directory_path = ‘/Users/oltjano/Desktop/EngineeringStudent’

Once you have made sure that you have declared the correct path of the directory you want to pass as an argument in the listdir utility, then run the Python command which is shown in the following example.


After the above command gets executed, a list object is being returned. The list object contains all the files found in the directory.

The following is the list object which I got after the above Python command got executed in the interactive Python shell of my Mac OS X machine.

[‘.DS_Store’, ‘Inxh informatike’, ‘Matlab’, ‘Programming’]

Final thoughts

There are many other ways to accomplish the same task in the Python computer programming language. Based on my experience with the Python technology so far, os.listdir utility is a great one when it comes to listing the content inside directories as it returns a list object which can be later utilized in the Python application.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Leave a Reply

Your email address will not be published. Required fields are marked *