问题:
我正在处理一个文件元项目,它从文件夹中收集文件信息并将其存储在JSON文件中。
My Empty JSON文件如下所示
db.json
{
"samples" : []
}
现在我的想法是扫描每个文件并将每条记录插入到样本数组中,如下所示
db.json
{
"samples" : [
{
"file_name": "ba18524fe5d5c6e99b99c7da66dbbfa094ab8f61",
"file_new_location": "/home/admin/",
"file_path": "/home/admin/vt_files/ba18524fe5d5c6e99b99c7da66dbbfa094ab8f61",
"file_source": "VT",
"md5": "149c4ac4ba0863607e033d6a5721fee7",
"mime": "application_x-dosexec",
"severity": "high",
"sha256": "50bc946af55f0a5deb66f935229046c1ec74fb2233d71efa3ae064a073a771f5"
}
]
}
但我的问题是,当我尝试插入记录时,我无法插入到样本中,但是只是在一行中。
for file_original_name in files:
file_meta = {}
file_meta['file_name'] = file_original_name
file_meta['file_path'] = os.path.join(root,file_original_name)
file_meta['file_source'] = source
file_meta['severity'] = severity
file_meta['md5'] = md5(file_meta['file_path'])
file_meta['sha256'] = sha256(file_meta['file_path'])
mime = magic.Magic(mime=True)
file_meta['mime'] = mime.from_file(file_meta['file_path']).replace('/','_')
file_meta['file_new_location'] = '{}/{}/{}/{}'.format(default_root,severity,file_meta['mime'],file_original_name)
try:
extracted_new_dir = os.path.join(default_root,severity,file_meta['mime'])
if not os.path.isdir(extracted_new_dir):
os.makedirs(extracted_new_dir)
if delete:
move(file_meta['file_path'],file_meta['file_new_location'])
else:
copyfile(file_meta['file_path'],file_meta['file_new_location'])
print json.dumps(file_meta,sort_keys=True,indent=4)
except Exception as e:
print e
result[file_original_name] = (file_meta)
with open('db.json','a') as f:
json.dump(result , f)
有关如何解决此问题的任何建议?
答案 0 :(得分:0)
首先尝试格式化结果,然后再将其写入文件:
result = json.dumps(r, indent=4)
with open('db.json','a') as f:
f.write(result)