How to obtain a list of files in a directory in Python?

Python can utilize the listdir function from the os module to obtain a list of files in a directory. The listdir function takes one parameter, which is the directory path, and returns a list containing the names of all files and folders in that directory.

Here is a sample code:

import os

# 获取当前目录下的文件和文件夹列表
file_list = os.listdir('.')
print(file_list)

# 获取指定目录下的文件和文件夹列表
file_list = os.listdir('/path/to/directory')
print(file_list)

The above code first uses ‘.’ to represent the current directory, then calls the listdir function to get a list of files and folders in the current directory. Next, it uses ‘/path/to/directory’ to represent a specified directory, and then calls the listdir function to get a list of files and folders in that directory.

bannerAds