How can you view all the files in a folder using Python?

In Python, you can use the listdir() function from the os module to view all files in a folder. Here is an example code:

import os

# 指定文件夹路径
folder_path = '/path/to/folder'

# 获取文件夹下的所有文件
files = os.listdir(folder_path)

# 遍历打印所有文件
for file in files:
    print(file)

In the code above, the variable folder_path specifies the path of the folder. The os.listdir() function will return a list containing all the files and folders in the folder. We can then use a loop to print out the name of each file.

bannerAds