OSError: [Errno 22] Invalid argument: 'The Game (John Smith)n.txt'

Question:

Line 37:

  with open("{}.txt".format(cb), 'w', encoding="utf8") as wrt:

OSError: [Errno 22] Invalid argument: ‘The Game (John Smith)n.txt’

I am trying to write files and name them according to the book title. I believe I get the error above because of the "n" in the title, I have tried to remove it, with no luck. Here is the part of the code that generates the error

#Convert book title into string
            title = str(cb)
            title.replace("n",'')
            title.strip()
#write the book notes in a new file
            with open("{}.txt".format(cb), 'w', encoding="utf8") as wrt:
                wrt.write(content)
                wrt.close

I know this is where the error is because if I give the file a title it works just fine.
cb is just a variable for current book equal to a list value, cb is defined once the list value is matched from lines read from a text file. I successfully write a new text file with "content" selectively gathered from a previous text file.

Asked By: Mario Tomas

||

Answers:

You are using replace without assigning it to a variable, remember that strip and replace do not change the variable in place. This should work:

title = title.replace("n",'')
title = title.strip()
with open(f"{title}.txt", 'w', encoding="utf8") as f:
    f.write(content)
Answered By: daaawx

If the variable that stores the title of the book in the form of a string is title then maybe you should pass that as argument while formatting the name of the file that you have to open: with open("{}.txt".format(title), 'w', encoding="utf8") as wrt:

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.