How to print all files within a directory using Python?

Published on Aug. 22, 2023, 12:15 p.m.

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.

Tags:

os