Learning Python : Print All File Names In A Folder | Java Inspires



 Hi Guys,

Welcome to Java Inspires..

In this post, we will see how to print all the file names and sub-folder names in a folder using python os library.



scratch.py

#JavaInspires
#required imports
from os import listdir
from os import path

#file path from where to read all files and folders
filepath = "C:\\Users\\#JavaInspires\\Desktop\\testfolder"

for file in listdir(filepath):
    if path.isfile(path.join(filepath,file)):
        print('file:',file)
    elif path.isdir(path.join(filepath,file)):
        print('dir:',file)




#end


Output:

C:\Users\#JavaInspires\AppData\Local\Programs\Python\Python39\python.exe C:/Users/#JavaInspires/AppData/Roaming/JetBrains/PyCharmCE2020.2/scratches/scratch.py
file: testfile_1.txt
file: testfile_2.txt
file: testfile_3.txt
file: testfile_4.txt
dir: testFolder
dir: testFolder - Copy

Process finished with exit code 0


Screenshots:


Output


Thank You 😊

key words: print all file names in a folder python, 


Post a Comment

Previous Post Next Post