How to list all files of a directory in Python and add them to a list?

0
0

In Python, you can list all the files in a directory using the os module. The os module provides a function called listdir() that can be used to list the files and directories in a directory. Here’s an example:

import os

# Get a list of all files in the directory
files = os.listdir(‘/path/to/directory’)

# Filter out directories and add files to a list
file_list = []
for file in files:
if os.path.isfile(os.path.join(‘/path/to/directory’, file)):
file_list.append(file)

In this example, os.listdir() is used to get a list of all the files and directories in the directory. The os.path.isfile() function is used to check if each item in the list is a file, and if it is, the file is added to a new list called file_list. The os.path.join() function is used to join the directory path and the file name, so that the os.path.isfile() function can check if the item is a file.

Alternatively, you can use a list comprehension to achieve the same result in a more concise way:

import os

# Use a list comprehension to get a list of all files in the directory
file_list = [f for f in os.listdir(‘/path/to/directory’) if os.path.isfile(os.path.join(‘/path/to/directory’, f))]

 

This code creates a list of all files in the directory using a list comprehension. The if statement in the list comprehension filters out directories, so the resulting list only contains files. The os.path.join() function is used to join the directory path and the file name, so that the os.path.isfile() function can check if the item is a file.

  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.