[英]how to rename json file using python
我想將新創建的 json 文件另存為更新名稱的新文件,例如,原始文件名為
update.json
我想要的是
{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)
非常感謝
您可以使用格式字符串在文件名中傳遞新 ID 的值。
newId = 'Your ID here'
with open(f"./{newId}_update.json", "w") as jsonFile:
json.dump(data, jsonFile)
像這樣的事情應該做的工作:
data["Id"] = "newid"
newname = "./"+data["Id"]+"_update.json"
with open(newname, "w") as jsonFile:
json.dump(data, jsonFile)
現在您將新文件保存在update.json.json
下。 在open
function 中,可以選擇將新文件寫到哪里。 所以在你的情況下,它可能是這樣的
# 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)
請注意,這不會刪除以前的文件。 如果你想覆蓋以前的文件,那么你可以這樣做:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.