I am working with a JSON file which needs to be read, edited and saved. Its content is the following:
{
"images_src": [
"img-1.jpg",
"img-2.jpg",
"img-3.jpg",
],
"scheme": "https",
"host": "www.list-em.com"
}
I'm using (more or less) the following code to do so:
file = open('file.json', "r+")
data = json.load(file)
data['images_list'] = []
file.truncate(0)
json.dump(data, file)
file.close()
Which results in the file being saved like this (I'm only showing a part, for illustrative purposes, since it's a very long output -i.e: 189 lines-)
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 7b0d 0a20 2020 2022
7061 796c 6f61 6422 3a20 7b0d 0a20 2020
2020 2020 2022 6163 6365 7373 5f74 6f6b
Now, doing some research I found out this solution for editing JSON files, and it's working as expected. So my question is more for understanding the reason behind the behavior I was getting with my method.
I thought that when I did this: file.truncate(0)
, I was truncating the file's content from the initial position, so now I would have an empty file, ready to dump the new JSON data. I mean, I thought that by using truncate(0)
I wouldn't need to use seek(0)
, but apparently it's not how it works.