How can I make a short program to list the names of files and sub-directories in a directory?

I have a heavy laden C: Drive and I want to get a list of files present in the Documents directory and Downloads directory. How can I write a program for this ?

Add Comment
1 Answer(s)

import os

def list_files_and_directories(path):
for name in os.listdir(path):
if os.path.isfile(os.path.join(path, name)):
print(f'{name} is a file.’)
else:
print(f'{name} is a directory.’)

# Call the function with the directory path
list_files_and_directories(“/path/to/your/directory”)

 

replace "/path/to/your/directory" with the actual path of the directory you want to inspect.

 

Answered on August 3, 2023.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.