Python Practice › OS Module Programs › Program 34
Create files with 10 extensions
Write a Python program to create sample files with 10 different extensions.
Output
10 ['sample.csv', 'sample.html', 'sample.ini', 'sample.json']
Approach
- Loop over a list of extensions.
Solution
import os os.makedirs("fake", exist_ok=True)extensions = ["txt", "csv", "json", "py", "md", "log", "xml", "html", "yaml", "ini"]for ext in extensions: with open(os.path.join("fake", f"sample.{ext}"), "w") as f: f.write(f"sample {ext} data\n")print(len(os.listdir("fake")), sorted(os.listdir("fake"))[:4])Output
10 ['sample.csv', 'sample.html', 'sample.ini', 'sample.json']
Learn the concept
New to this topic? Read the lesson, then come back.