python

Show all files in a dictionary as a list in Python

In this post, we are explaining methods and techniques that can be used to get all the files as list items using Python.

from os import listdir
from os.path import isfile, join

all_files = [item for item in listdir('FOLDER_PATH') if isfile(join('FOLDER_PATH', item))]

# -> ['file1.txt', 'file2.txt', 'file3.txt']

we are using listdir() function from the Python os module. This function will list all the directories and files that exist inside a folder. To filter only files we are using the isfile() function from os.path.

List all file and folders inside a dictionary

We can use listdir() function of the os module to list all the files and directories that exist inside a directory.

How os.listdir() function works

The os.listdir() function will get all the directories and files from the given path of the directory and create a list that will contain the names of directories and files as list items. You can iterate through the list to get the names of the folders and files.

Syntax

os.listdir(DIRECTORY_PATH)

Code Example

Given the code example that takes a directory path as a parameter and returns the list of folders and file names.

all_files_and_folders = os.listdir('usr/documents/')

Output

['data', 'file1.json', 'file2.txt', 'file3.txt']

Get only text(.txt) files from the list

You can also use the glob module to get all the text files that have an extension .txt with it. It takes the directory path as a parameter and returns the text file names list.

Code example

import glob

result = glob.glob("/home/usr/*.txt")

print(result)

if you want to get only JSON files from a directory you can use the below code example. 

import glob

result = glob.glob("/home/usr/*.json")

print(result)
Was this helpful?