【发布时间】:2019-12-30 13:15:13
【问题描述】:
我有一个 .json 文件,我想将数据附加到该文件中。但前提是此字符串不在 .json 文件中。
JSON 文件:
[{"filename":"file1"}, {"filename":"file2"}, {"filename":"file3"}]
最终结果 JSON 文件:
[{"filename":"file1"}, {"filename":"file2"}, {"filename":"file3"}, {"filename":"file4"}]
我目前有这个:
with open('gdrivefiles.json', 'r') as f:
filenameslist = json.load(f) #Loads the .json file into a string (If I'm right)
for distro in filenameslist:
filenames = distro["filename"] #Gets a list of all the filenames
if name in filenames:
print("yes") #If name is in the list of filenames print 'yes'
else:
print("no") #If name is in the list of filenames print 'no'
(这段代码放在一个for循环中,所以它会为name的每个新值运行这段代码)
如果 json 文件中还没有 name ({"filename":"name"}),我该如何添加它?
【问题讨论】:
-
这能回答你的问题吗? How to append data to a json file?
标签: python arrays json python-3.x visual-studio-code