Python Practice › OS Module Programs › Program 6
Create 10 folders with random names
Write a Python program to create 10 directories with random names.
Output
10 ['dissyk', 'dwtgml', 'fkaflm']
Approach
- Build random names with
random.choicesand create each folder.
Solution
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.