How to list All files in a directory in Python

If you are working with files and directories in Python, sometimes you ask these question:

  • What is the best way to list all files and directories in Python
  • How can I add all the files in a List in Python
  • How can I add all the directories in a List in Python
  • How to visit all the files in a directory in Python

Here I’ll show some example that answers above questions.

List all files and directories in Python

You can use os.listdir(), if you want to list all the files and directories. This function is very useful and efficient. It will give you everything that is in the directory (including files and directories). This function even includes hidden files and files with only extnsion and no filenames. Here is a syntax to use os.listdir().

import os
dir_n_files = os.listdir()

Now, you can same function in Python 2.7 but there is a small difference. For Python 2, you have to pass the folder name as an argument. Here is the syntax for Python 2.7. Here ‘ .' means look for files and folders in current directory.

import os
dir_n_files = os.listdir('.')

Add only files in a List

If you want to create a list of files in a folder, you can use glob package. It parse files in the folder and returns list. It also takes parameter, which is helpful in filtering out unwanted files.

For example if you have 100s of files in a folder and they are of mix extension. You want to write a Python script that should only list .json files. you can pass a parameter to list only .json files. Here is the syntax.

import glob
json_files = glob.glob("*.json")

Now if you want to add all 100 files in a list, you can just change the parameter from "*.json" to "*.*".

Scroll to Top