I would like to save new created json file as a new one with an updated name, for example, 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
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)
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)
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)
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.