Create 10 folders with random names

EasyOS Module Programs · 6 of 49

Write a Python program to create 10 directories with random names.

Advertisement
Output
10 ['dissyk', 'dwtgml', 'fkaflm']

Approach

  1. Build random names with random.choices and create each folder.

Solution

Python
import osimport randomimport string random.seed(1)os.makedirs("random_dirs", exist_ok=True)for _ in range(10):    name = "".join(random.choices(string.ascii_lowercase, k=6))    os.makedirs(os.path.join("random_dirs", name), exist_ok=True)print(len(os.listdir("random_dirs")), sorted(os.listdir("random_dirs"))[:3])
Output
10 ['dissyk', 'dwtgml', 'fkaflm']

Line by line

Line 5

The seed makes the names repeatable; remove it for new names each time.

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