I have 25 json files in a folder, named 0.json through 24.json, and I am trying to batch open and rename a perimeter "image" inside of each, which currently all have a placeholder of "https://" in the "image" field.
I have a central folder on a site like dropbox, that has a url structure of https://weburlofnewimage/0, /1, /2 etc. And so I would like to open each file, and change the value of the "image" key to be replaced with "https://weburlofnewimage/ + current file number + '.png'".
The .json currently appears as follows for each json file:
{"image": "https://", "attributes": [{"trait_type": "box color", "value": "blue"}, {"trait_type": "box shape", "value": "square"}]}
but should be
{"image": "https://weburlofnewimage/0", "attributes": [{"trait_type": "box color", "value": "blue"}, {"trait_type": "box shape", "value": "square"}]}
So far I have tried the following, but I believe I am going down a rabbit hole
import json
import os
folderPath = r'/path/FolderWithJson'
fileNumber = 0
for filename in os.listdir(folderPath):
with open(filename, 'r') as f:
data = json.load(f)
data['id'] = str('https://weburlofnewimage/' + str(fileNumber) + '.png')
os.remove(filename)
with open(filename, 'w') as f:
json.dump(data, f, indent=4)
fileNumber +=1
and have tried:
import os
import json
folderPath = r'/path/FolderWithJson'
fileNumber = 0
for filename in os.listdir(folderPath):
with open(filename, 'r+') as f:
data = json.load(f)
data['image'] = str('https://weburlofnewimage/' + str(fileNumber)
f.seek(0)
json.dump(data, f, indent=4)
f.truncate() # remove remaining part
fileNumber +=1
However, in both cases I get the following error:
FileNotFoundError: [Errno 2] No such file or directory: '20.json'
However, the file is indeed in that directory...