import os # Define the directory path dir_path = "C:/my_directory" # Get a list of all files in the directory files = os.listdir(dir_path) # Print the file names for file in files: print(file)
To list all files in a directory in Python, you can use the os module and the listdir() method.
Note that this will only include files in the top-level directory, not any files in subdirectories. To include files in subdirectories as well, you can use the os.walk() method, like this:
import os # Define the directory path dir_path = "C:/my_directory" # Use os.walk() to get a list of all files in the directory and its subdirectories for root, dirs, files in os.walk(dir_path): # Print the file names for file in files: print(os.path.join(root, file))This will print the names of all the files in the specified directory and all its subdirectories. The os.path.join() method is used to combine the directory path and the file name to form the full file path.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.