Python Code to List all Files from Desired Folder
To get list of files present in a computer folder to a string variable, use the code below.
Edit the folder path mentioned in the variable “folder_path”. Then execute this ready to use code.
It will print the file name one by one.
Here is the code List Files:
#import Libraries import os,sys #Enter Folder Path folder_path = 'C:/' #To Get Folder path from Command line if len(sys.argv) == 2: folder_path = sys.argv #Get File details to a list file_list = os.listdir(folder_path) #Read File one by one for file_name in file_list: print(file_name) #Program End print("Program Completed")
The output will look something like this:
- Program completed
- File List by Extension or Type:
Python – List Files Filtered by File Type
This code does not fetch the file names filtered by extension or file type.
To do that, include this if condition just below the for loop.
This ensures that only the files ending with this extension are picked up for processing.