I am unable to create multiple files with this code, what is wrong?

Question:

So I’m trying to write a program that takes names from a list and adds it to a letter. A text file is created for each name for the letter however the code seems to stop working at that point.

letter = []
names = []
file = open("Input/Letters/starting_letter.txt", "r")
letter = file.readlines()
file.close()
name1 = open("Input/Names/invited_names.txt", "r")
names = name1.readlines()
name1.close()
for name in names:
    create_letter = open(f"{name}.txt", "w")
    for line in letter:
        line = line.replace("[name],", f"{name},")
        create_letter.write(line)
    create_letter.close()

I get the error message

Traceback (most recent call last):
  File "C:UsersDefault UserPycharmProjectsMail Merge Project Startmain.py", line 10, in <module>
    create_letter = open(f"{name}.txt", "w")
OSError: [Errno 22] Invalid argument: 'Aangn.txt'

Is there a problem with the way I am creating the files?

Asked By: Sulav Rai

||

Answers:

You can’t have newlines in your file name. It is invalid in your OS/filesystem.

Remove them with:

open(f"{name.strip()}.txt", "w")

Or:

open(f"{name.replace('n', '')}.txt", "w")
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.