Print name, path and type

EasyOS Module Programs · 35 of 49

Write a Python program to print the name, path and type (file or folder) of everything in a folder.

Advertisement
Output
Name : TestFolder
Path : target\TestFolder
Type : Folder
Name : testdata.txt
Path : target\testdata.txt
Type : File

Approach

  1. os.scandir entries know their name, path and type.

Solution

Python
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.

More os module programs

← All 49 OS Module Programs

Leave a Comment