0

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.

  • 2
    The string `.replace()` function does not modify the existing string; it returns a _new_ string. So you need to do `title = title.replace("\n",'')`. – John Gordon Nov 08 '20 at 06:39

2 Answers2

1

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:

0

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)
daaawx
  • 3,273
  • 2
  • 17
  • 16