How to Create a List of Files in Python?

Estimated read time 2 min read

To create a list of files in Python, you can use the os module to interact with the file system. Here’s an example code that creates a list of all the files in a directory:

import os

# define the directory path
dir_path = "/path/to/directory"

# get a list of all the files in the directory
files_list = os.listdir(dir_path)

# print the list of files
print(files_list)

In this example, we first import the os module. Then we define the directory path as a string and assign it to the dir_path variable. We use the os.listdir() function to get a list of all the files in the directory, and assign it to the files_list variable. Finally, we print the list of files using the print() function.

Note that the os.listdir() function returns both files and directories in the specified directory. If you only want to get a list of files (excluding directories), you can use a list comprehension to filter out the directories:

import os

# define the directory path
dir_path = "/path/to/directory"

# get a list of all the files in the directory (excluding directories)
files_list = [f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))]

# print the list of files
print(files_list)

In this example, we use a list comprehension to create a new list that contains only the files (not directories) in the specified directory. The os.path.isfile() function is used to check if a file is a regular file (not a directory), and the os.path.join() function is used to join the directory path with each file name in the list.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply