深度阅读

How to print all files within a directory using Python?

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

To print all files within a directory using Python, you can use the os module’s listdir() method to get a list of all files and directories within the specified directory, and then loop through the list to print the names of each file. Here’s an example:

import os

directory = '/path/to/directory'  # Replace with the path to your directory

# Get a list of all files and directories within the specified directory
files = os.listdir(directory)

# Loop through the list and print the names of each file
for filename in files:
    print(filename)

In this example, we first specify the path to the directory we want to print the files for by setting the directory variable. We then use the os.listdir() method to get a list of all files and directories within the specified directory. Finally, we loop through the list of files and print the name of each file to the console using the print() function.

You can also use other methods in the os module to manipulate files and directories in various ways.

相关标签

博客作者

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