I am trying to replace all square brackets with braces as it's easier to convert for other use in other languages (such as Lua). The issue is, is that none of the square brackets get replaced with braces. I even did a find search in the file to see if there were any braces but none at all. The code below is just a simple pixel-color code using Python Pillow.
import json
from PIL import Image
img = Image.open('favicon-8.png')
rgb_im = img.convert('RGB')
sizeX, sizeY = img.size
pixels = []
def getcolors():
for x in range(1,sizeX):
for y in range(1,sizeY):
r,g,b = rgb_im.getpixel((x,y))
pixels.append([r,g,b])
getcolors()
jsonStr = json.dumps(pixels)
with open("imgoutput.json", "a+") as output:
output.write(jsonStr)
filedata = output.read()
filedata.replace('[','{')
filedata.replace(']','}')
You have to move your read pointer position within the file.
Test code:
with open("hello.txt", "a+") as fp:
fp.write("Hello World!")
strdata = fp.read()
print("Test1: %s" % strdata)
fp.seek(0,0)
strdata = fp.read()
print("Test2: %s" % strdata)
Results:
Test1:
Test2: Hello World!
You're only replacing stuff in the variable filedata
, you need to write the changes to your .json
file. For this you can use x.write(filedata)
...
with open("imgoutput.json", "r") as output:
filedata = output.read()
filedata = filedata.replace('[','{')
filedata = filedata.replace(']','}')
input = open("imgoutput.json", "w")
input.write(filedata)
input.close()
Something to note; .replace()
doesnt change the active variable, it makes a new one. So the correct syntaxs is a = b.replace() || a = a.replace
a = b.replace() || a = a.replace
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.