List everything in a folder

EasyOS Module Programs · 13 of 49

Write a Python program to list all the files and folders in a target path.

Advertisement
Output
['a.txt', 'b.csv', 'sub']

Approach

  1. os.listdir() returns names; sort them for a stable order.

Solution

Python
import os os.makedirs("target/sub", exist_ok=True)for name in ["a.txt", "b.csv"]:    open(os.path.join("target", name), "w").close()print(sorted(os.listdir("target")))
Output
['a.txt', 'b.csv', 'sub']

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