乐闻世界logo
搜索文章和话题

How do I list all files of a directory using python?

1个答案

1

In Python, we can use the os module to list all files in a directory. The os module provides various methods to interact with the operating system, such as reading files and traversing directories. Below is an example using the os.listdir() method from the os module to list all files (including subdirectories) in a specified directory:

python
import os def list_files(directory): # Ensure the provided path exists if os.path.exists(directory): # os.listdir(directory) lists all files and subdirectories in the directory files = os.listdir(directory) # Print all files and subdirectories for file in files: print(file)

Assuming we want to list files in the current directory: current_directory = '.' list_files(current_directory)

In the above example, we first import the os module. We define a function list_files() that accepts a parameter directory, which is the path to the directory we want to list files from. Inside the function, we first check if the path exists (using os.path.exists()). If the path exists, we call os.listdir(directory) to retrieve all files and subdirectories in the directory, then iterate through this list and print the name of each item.

This method lists all files and subdirectories. If you only want to list files, you can add a check during iteration to determine which items are files:

python
import os def list_files_only(directory): # Ensure the provided path exists if os.path.exists(directory): # os.listdir(directory) lists all files and subdirectories in the directory items = os.listdir(directory) # Use os.path.isfile to check if an item is a file files = [item for item in items if os.path.isfile(os.path.join(directory, item))] # Print all files for file in files: print(file)

In this modified function, we use list comprehension and the os.path.isfile() method to filter out only the items that are files, then print these files.

2024年6月29日 12:07 回复

你的答案