0

I have a code that needs to read a JSON file with multiple lines, i.e:

{"c1-line1": "value", "c2-line1": "value"}
{"c1-line2": "value", "c2-line2": "value"}...

and, after change the keys values (already working), I need to write a new json file with these multiple lines, i.e:

{"newc1-line1": "value", "newc2-line1": "value"}
{"newc1-line2": "value", "newc2-line2": "value"}...

My problem is that my code are just writing the last value readed:

{"newc1-line2": "value", "newc2-line2": "value"}

My code:

def main():
   ... # changeKeyValueCode
   writeFile(data)
 
def writeFile(data):
   with open('new_file.json', 'w') as f:
       json.dump(data, f)
 
 

I already tried with json.dumps and just f.write('') or f.write('\n')

I know that data in writeFile() is correctly with each line value.

How can I resolve this, please?

1
  • 1
    open('new_file.json', 'w') opens file for writing, if you call writeFile in a loop it will overwrite previous content, try calling open with a flag, to append, so it will look like this: open('new_file.json', 'a'). Anyway, opening file in a loop isn't that good, if this is the case. Commented Mar 25, 2022 at 12:55

1 Answer 1

2
def main():
   ... # changeKeyValueCode
   writeFile(data)
 
def writeFile(data):
   with open('new_file.json', 'a') as f:
       json.dump(data, f)

with open('new_file.json', 'a')

open file with (a), it will search the file if found append data to the end, else it will create empty file and then append data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.