Home > OS >  OSError: [Errno 22] Invalid argument with a \r
OSError: [Errno 22] Invalid argument with a \r

Time:09-06

I use JSON to make .txt files but when I make them with this

with open("Saves/"   setname   ".txt", "w") as savefile:
    json.dump(data, savefile)

... I get this:

Traceback (most recent call last):
  File "c:\Users\creep\OneDrive\Bureaublad\Oyunlar\Retraich\main.py", line 647, in <module>
    new_save()
  File "c:\Users\creep\OneDrive\Bureaublad\Oyunlar\Retraich\main.py", line 448, in new_save
    with open("Saves/"   setname   ".txt", "w") as savefile:
OSError: [Errno 22] Invalid argument: 'Saves/hello\r.txt'

I tried setting them in a function. No code adds that \r in the file name as well (and I think that that is where the error arises from). I tried setting them in a define function and still not working. And the setname variable is Hello

CodePudding user response:

setname is initialized to "hello\r". A carriage return (\r) is not a valid character in Windows file paths. You can avoid this by trimming invalid codepoints from your string:

setname = setname.strip("<>:\"\\/|?*\r\n")
  • Related