How to retrieve all file names in a specified directory using Python?

You can use the os.listdir() function to obtain all file names in a specified directory. This function will return a list containing the names of all files and directories in the directory. For example, the following code will retrieve all file names in the current directory (“.”):

import os

file_names = os.listdir(".")
print(file_names)

To access the file names in a different directory, simply pass the directory path as a parameter to the os.listdir() function. For example, the following code will retrieve all file names in the /path/to/directory directory:

import os

directory = "/path/to/directory"
file_names = os.listdir(directory)
print(file_names)

Please note that the os.listdir() function will return the names of all files and directories in a directory, including hidden files and directories. If you only want to retrieve file names excluding subdirectories and hidden files, you can use the os.path.isfile() function to filter the results. The following code will only retrieve file names in the specified directory:

import os

directory = "/path/to/directory"
file_names = [file for file in os.listdir(directory) if os.path.isfile(file)]
print(file_names)
bannerAds