我有一个JSON文件,如下所示:
{
"files": [
{
"nameandpath": "/home/test/File1.zip",
"MD5": "e226664e39dc82749d05d07d6c3078b9",
"name": "File1"
},
{
"nameandpath": "/home/test/File2.zip",
"MD5": "dbb11b2095c952ff1d4b284523d3085f",
"name": "File2"
}
]
}当条件为真时,我希望只更新两行: true、wish和MD5。条件是,如果测试的文件存在于JSON文件中:我将更新该行,否则将使用它的3个值添加该文件。
{
"files": [
{
"nameandpath": "/home/test/File1.zip",
"MD5": "e226664e39dc82749d05d07d6c3078b9",
"name": "File1"
},
{
"nameandpath": "/home/test/File2.zip",
"MD5": "dbb11b2095c952ff1d4b284523d3085f",
"name": "File2"
}
# block added because the file tested wasn't present in json file
{
"nameandpath": "/home/test/File3.zip",
"MD5": "dbb11b2095c952ff1d4b284523d3085f",
"name": "File3"
}
]
}我无法更新现有行,也无法测试添加新行。
你能帮帮我吗?
我怎么能做这样的事情呢?
到目前为止我的代码如下:
# getting file name
# getting MD5 of the file
jsonfile = "/home/test/filesliste.json"
with open(jasonfile, "r+") as json_file:
data = json.load(json_file)
for tp in data['files']:
if tp['name'] == name:
if tp['MD5'] == fileMD5:
print("same MD5")
# adding this file to json file
else:
print("NOT THE same MD5")
# updating the file info into json file发布于 2017-01-19 19:05:38
我不清楚你到底在纠结什么。下面是我将如何组织代码,也许这会有所帮助:
jsonfile = "/home/test/filesliste.json"
# read json file
with open(jsonfile) as f:
data = json.load(f)
# find index of file or -1 if not found
index = -1
for i, tp in enumerate(data['files']):
if tp['name'] == name and tp['MD5'] == fileMD5:
index = i
break
# update data
# we're lazy and just delete the old file info, then re-add it
if index >= 0:
del data['files'][index]
tp = {
"name": ...,
"nameandpath": ...,
"MD5": ...,
}
data.append(tp)
# write data back to file
with open(jsonfile) as f:
# json.dump or something like thatMD5
不应该再使用MD5,因为它被认为是损坏的。如果可能,您应该将其替换为SHA-2或SHA-3,它们类似,但更安全。
https://stackoverflow.com/questions/41725242
复制相似问题