What function is used to list files in a directory in Python?
a) os.listdir()
b) os.walk()
c) shutil.listdir()
d) os.scandir()
Answer:
a) os.listdir()
Explanation:
The os.listdir()
function in Python is used to list all files and directories in a specified directory. If no directory is specified, it returns the list of files and directories in the current working directory.
import os
# Example of listing files in a directory
files = os.listdir(".")
print(files) # Output: ['file1.txt', 'file2.txt', 'directory1']
In this example, the os.listdir()
function lists all files and directories in the current directory, represented by "."
.
Listing files is useful for tasks such as iterating over files for processing, displaying directory contents, or organizing files programmatically.