深度阅读

How to list files in a directory in Python using os.listdir()?

作者
作者
2023年08月22日
更新时间
12.64 分钟
阅读时间
0
阅读量

You can use the os.listdir() method in Python to list all the files and directories in a specific directory. Here’s an example code snippet:

import os

folder_path = '/path/to/directory'

# List all the files and directories in the given path
content_list = os.listdir(folder_path)

# Output the list of contents
print(content_list)

This should output a list of all the files and directories in the specified directory path. If you want to list only the files you can use the following code snippet:

import os

folder_path = '/path/to/directory'

# List all the files in the given path
file_list = [
    f for f in os.listdir(folder_path)
    if os.path.isfile(os.path.join(folder_path, f))
]

# Output the list of files
print(file_list)

This code will only list the files in the specified directory path and exclude any directories that might be present within it. You can modify the condition in the list comprehension to include other filters as per your needs.

Keep in mind that os.listdir() only lists the contents of a directory and does not recurse into other directories within that directory. If you need to get a recursive listing of all the contents in a directory, you can look into using the os.walk() method instead.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。