0

I'm trying to make script that generates 26 text files named a.txt, b.txt, and so on up to z.txt. Each file should contain a letter reflecting its filename. So, a.txt will contain letter a, b.txt will contain letter b and so on.

How I need to change this code that it generates .txt files? Now the script is almost correct but it doesn't make .txt files. I'm using Python 3.5. Here is my code:

import string
alphabet= string.ascii_lowercase
for letter in alphabet:
    with open(letter,'w') as file:
        file.write(letter)

3 Answers 3

1

you need to do this-

import string
alphabet= string.ascii_lowercase
for letter in alphabet:
    with open(letter+".txt",'w') as file:
        file.write(letter)
Sign up to request clarification or add additional context in comments.

Comments

1

Construct the file name using string formatting. str.format() is the preferred way to perform string formatting:

import string

for letter in string.ascii_lowercase:
    with open('{}.txt'.format(letter), 'w') as f:
        f.write(letter)

N.B. Although this is not a problem in Python 3 you should try to avoid using the name file as a variable, it shadows the Python 2 builtin file object, and potentially makes your code less portable.

Comments

0
for i in range(0,26):
    alphabetLeter = chr(65+i)
    with open(f"{alphabetLeter}.txt", 'w') as fio:
        print(f"{alphabetLeter}.txt")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.