0

This gives me an error:

with open('username.json', "r+") as f:
    json.dump(current_contents, f)
    newlist= json.load(f)
print(newlist)



json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

This works:

with open('username.json', "r+") as f:
    json.dump(current_contents, f)

with open('username.json') as f:
    current_contents = json.load(f)
print(current_contents)

But I have to open up 2 'with' blocks to do it. What's the point of "r+" if it can't read and write within the same block?

  • You _can_ do both things, but you need to `seek()` to get back to the start of the file between them. Either reading or writing moves the location inside the file you're operating at; if your cursor is at the end of the file when you try to read, there's nothing between it and the end of the file so it always comes back empty. – Charles Duffy Oct 20 '21 at 21:28
  • `r+` makes more sense for binary files, where you might be reading and writing *fixed*-size blocks at arbitrary locations. The "blocks" in a text file correspond to lines, which typically don't have a fixed size. (That's why you use `\n` as a delimiter, rather than assuming a line is `N` characters/bytes long. – chepner Oct 20 '21 at 21:31
  • BTW, this is also the same problem as https://stackoverflow.com/questions/5444809/python-temporaryfile-returns-empty-string-when-read, despite TemporaryFile being used there and not here. – Charles Duffy Oct 20 '21 at 21:35
  • Thank you. the seek function works out great! – codingnewtoworking3 Oct 20 '21 at 21:55

0 Answers0