I would like to save json file as a new one with updated name, like the original file name is
update.json
what I want is
{newid_} update.json
#example:123_update.json
with open("./update.json", "r") as jsonFile:
data = json.load(jsonFile)
data["Id"] = "newid"
with open("./update.json", "w") as jsonFile:
json.dump(data, jsonFile)
Many thanks
CodePudding user response:
Something like this should do the work:
data["Id"] = "newid"
newname = "./" data["Id"] "_update.json"
with open(newname, "w") as jsonFile:
json.dump(data, jsonFile)
CodePudding user response:
You can pass the value of the new ID in the file name using format string.
newId = 'Your ID here'
with open(f"./{newId}_update.json", "w") as jsonFile:
json.dump(data, jsonFile)
CodePudding user response:
Right now you are saving the new file under update.json.json
.
In the open
function, is where you can choose where to write your new file.
So in your case, it could be something like
# Use a f-string to insert the new id into the file name
new_file_path = f"./{data['Id']}_update.json"
with open(new_file_path, "w") as jsonFile:
json.dump(data, jsonFile)
Note that this will not delete the previous file. If you wish to overwrite the previous file, then you can do something like:
import os
file_path = "update.json"
new_file_path = f"./{data['Id']}_update.json"
# Overwrite the content of the old file
with open(file_path, "w") as jsonFile:
json.dump(data, jsonFile)
# Rename it
os.rename(file_path, new_file_path)