Python Practice › File Handling Programs › Program 16
Create A.txt to Z.txt
Write a Python program to create text files named A.txt to Z.txt.
Output
26 ['A.txt', 'B.txt', 'C.txt'] Z.txt
Approach
- Loop over
string.ascii_uppercaseand create each file in a folder.
Solution
import osimport string os.makedirs("letters", exist_ok=True)for letter in string.ascii_uppercase: with open(os.path.join("letters", f"{letter}.txt"), "w") as f: f.write(f"This is file {letter}\n") files = sorted(os.listdir("letters"))print(len(files), files[:3], files[-1])Output
26 ['A.txt', 'B.txt', 'C.txt'] Z.txt
Line by line
Line 4
The files go into a separate folder to keep things tidy.
Learn the concept
New to this topic? Read the lesson, then come back.