replace() not replacing string contents of a file, even though file is defined as output

Question:

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.

In the last two lines, is where I try to attempt to replace all square brackets with braces, which doesn’t work.

with open("imgoutput.json", "a+") as output:
    output.write(jsonStr)
    filedata = output.read()

filedata.replace('[','{')
filedata.replace(']','}')
Asked By: vxsqi

||

Answers:

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

Answered By: Oskar

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!
Answered By: J. Choi
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.