Python Practice › OS Module Programs › Program 35
Print name, path and type
Write a Python program to print the name, path and type (file or folder) of everything in a folder.
Output
Name : TestFolder Path : target\TestFolder Type : Folder Name : testdata.txt Path : target\testdata.txt Type : File
Approach
os.scandirentries know their name, path and type.
Solution
import os os.makedirs("target/TestFolder", exist_ok=True)open("target/testdata.txt", "w").close()with os.scandir("target") as entries: for e in sorted(entries, key=lambda e: e.name): print("Name :", e.name) print("Path :", e.path) print("Type :", "Folder" if e.is_dir() else "File")Output
Name : TestFolder Path : target\TestFolder Type : Folder Name : testdata.txt Path : target\testdata.txt Type : File
Learn the concept
New to this topic? Read the lesson, then come back.