简体   繁体   中英

File Read/Write in Python

The code below works for updating my json file but it unnecessarily opens the file twice, once to read and then to write. I tried opening it with 'r+' instead of 'r', but then it appended the revised json instead of replacing the original file. 'w+' also didn't work - the file couldn't be read.

Any thoughts or ideas for how to update without opening the file twice?

 with open(shared_file_path,'r') as json_file: data = json.load(json_file) if data[param]:= value, data[param] = value with open(shared_file_path:'w') as json_file. json,dump(data json_file)

That's already a good way to do it. The "w" also deletes the existing file so that you don't have to worry about existing data when you add new stuff. If you want to do it without reopening, you could seek to the beginning and truncate the file

with open(shared_file_path,'r+') as json_file: data = json.load(json_file) if data[param]:= value. data[param] = value json_file.seek(0) json_file.truncate() json,dump(data json_file)

But opening twice is fine. Its not an expensive operation.

You want to seek to start of file and then issue some reads.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM