Python Practice › OS Module Programs › Program 13
List everything in a folder
Write a Python program to list all the files and folders in a target path.
Output
['a.txt', 'b.csv', 'sub']
Approach
os.listdir()returns names; sort them for a stable order.
Solution
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.