-1

I try to write a string to a file in Python and fail,

mystr = '{"a": "{\'a\': [\'b\': [\'\\saaaalam\\Mira.h\']}, {\'c\': [\'C:\\a\\t.exe\']}", "b": "open"}'

with open('test.json', 'w') as out_file:
   out_file.write(mystr)

The file "test.json" does not exist! However, if I for example remove an "a" in "saaalam" it works.

A Hansson
  • 77
  • 2
  • 9
  • your code works good for me. can you paste the error – shivankgtm Dec 21 '21 at 18:24
  • For me It worked just fine, I don't know if your json format is good but it saved for me the json file and the text in it as well – Kfir Goldfarb Dec 21 '21 at 18:25
  • Here is a cleaner way to define your variable: `mystr = r'''{"a": "{'a': ['b': ['\saaaalam\Mira.h']}, {'c': ['C:\a\t.exe']}", "b": "open"}'''`. It is easier to read without all those ```\'```. – accdias Dec 21 '21 at 18:28
  • Thanks, but for some reason it doesn't work for me. As I wrote, if I just change a single character, it works fine. – A Hansson Dec 21 '21 at 18:35

1 Answers1

1

Your code is working. You should check if python process has the right to create that file in your OS. In Linux and MacOS you can provide yourself access to write in the current directory with:

chmod 744 .

Another option is you are looking for your file at the wrong place. You should check the working directory in your IDE or try to run the script from the console.

Yevgeniy Kosmak
  • 3,561
  • 2
  • 10
  • 26
  • Judging by the drive letter in the string and all that backslashes, I guess the OP is on Windows and then `chmod` is not an option. – accdias Dec 21 '21 at 18:47
  • Maybe so, I hadn't thought that content of variable could mean something :) Then I'll just left [this](https://stackoverflow.com/questions/2928738/how-to-grant-permission-to-users-for-a-directory-using-command-line-in-windows) here. – Yevgeniy Kosmak Dec 21 '21 at 19:03