Create A.txt to Z.txt

EasyFile Handling Programs · 16 of 38

Write a Python program to create text files named A.txt to Z.txt.

Advertisement
Output
26 ['A.txt', 'B.txt', 'C.txt'] Z.txt

Approach

  1. Loop over string.ascii_uppercase and create each file in a folder.

Solution

Python
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.

More file handling programs

← All 38 File Handling Programs

Leave a Comment