-1

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

Plazm air
  • 1
  • 2
  • 4
    The contents of `setname` isn't valid, it contain a character that's not allowed. How do you initialize `setname`? If you need our help then please [edit] your question to show us a [mre]. – Some programmer dude Sep 05 '22 at 14:35
  • In this specific case you could just use `setname.rstrip('\r\n')` to be sure any newline/carriage return characters were removed. But odds are such a change is better at the source. – ShadowRanger Sep 05 '22 at 14:44
  • Welcome to Stack Overflow. Please read [ask] and https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ and https://meta.stackoverflow.com/questions/261592/ and [mre]. "No code adds that \r in the file name as well (and I think that that is where the error arises from)." Well, here is the code that creates the file name: `"Saves/" + setname + ".txt"`. Right? So, if `"Saves/" doesn't contain `\r`, and `".txt"` doesn't contain `\r`, then by process of elimination, it must be in `setname`. Right? So, **look at the code that gives `setname` its value**. – Karl Knechtel Sep 05 '22 at 14:46
  • (We cannot possibly do that, because it is not shown to us. My best **guess** is that `setname` has come from reading a file with e.g. `.readlines`, which leaves the line ending at the end of each line read from the file. In that case, please see [How to read a file without newlines?](https://stackoverflow.com/questions/12330522/how-to-read-a-file-without-newlines)) – Karl Knechtel Sep 05 '22 at 14:47

1 Answers1

0

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")
Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63