我该如何从dict向JSON文件添加2个相同的键,只使用screenshoturl2
和{
这是我现在的代码,它可以工作,但它只添加了第一个screenshoturl1
,而不是{
#!/usr/bin/env python3
import os
import sys
import json
import fileinput
def NumberofScreenshots():
global numberofscreenshots
while True:
try:
numberofscreenshots = input("Number of Screenshots?: ")
if numberofscreenshots == '':
print("Please enter how much screenshots to include.")
continue
elif numberofscreenshots.isalpha():
print("Please enter a number not a string.")
continue
else:
break
except ValueError:
break
def ScreenshotURL():
global screenshoturl1, screenshoturl2
if numberofscreenshots == "1":
screenshoturl1 = input("Screenshot URL: ")
elif numberofscreenshots == "2":
screenshoturl1 = input("Screenshot URL: ")
screenshoturl2 = input("Screenshot URL: ")
else:
pass
def NumberofScreenshots1():
if numberofscreenshots == "1":
with open('path/to/json/file','r') as f:
data = json.loads(f.read())
data['tabs'][0]['views'][1]['screenshots'][0]
data['tabs'][0]['views'][1]['screenshots'] = data['tabs'][0]['views'][1]['screenshots'][0]
data['tabs'][0]['views'][1]['screenshots'] = {"accessibilityText": "Screenshot","url": screenshoturl1,"fullSizeURL": screenshoturl1}
with open('path/to/json/file', 'w') as f:
f.write(json.dumps(data))
else:
print("Try again.")
def NumberofScreenshots2():
global data
if numberofscreenshots == "2":
with open('path/to/json/file','r') as f:
data = json.loads(f.read())
data['tabs'][0]['views'][1]['screenshots'][0]
print(data)
data['tabs'][0]['views'][1]['screenshots'] = data['tabs'][0]['views'][1]['screenshots'][0]
print(data)
data['tabs'][0]['views'][1]['screenshots'].update({"accessibilityText": "Screenshot","url": screenshoturl1,"fullSizeURL": screenshoturl1, "accessibilityText": "Screenshot","url": screenshoturl2,"fullSizeURL": screenshoturl2})
print(data)
with open('path/to/json/file', 'w') as f:
f.write(json.dumps(data))
else:
print("Try again.")
print("Pick Template:")
print("1. Default")
template = input("Template Name/Number: ")
if (template == "1"):
NumberofScreenshots()
ScreenshotURL()
NumberofScreenshots1()
NumberofScreenshots2()
# Show the user a error if they enter a number for a template that can't be found.
else:
print("The template you are looking for can not be found!")
我们正在查看名为NumberofScreenshots2
的函数
JSON文件:
^{2}$我希望它删除screenshots
中的所有内容,并使用用户在screenshoturl1
和screenshoturl2
中输入的用户输入重新添加,这样它将删除screenshots
中的占位符一样的所有内容,只添加2个用户在screenshoturl1
和{
谢谢!在
您可以将值设置为集合(如列表或元组)。为了方便起见,可以使用defaultdict。因此,如果您希望一个键有两个值:
这个输出:
^{pr2}$如果我理解你在这里想做什么,看起来你想更新一个或两个网址,一次一个。在
你能做的就是检查每个截图项目,一次一个,要么更新要么停止。这更容易,而且如果你想更新所有的文件。这也意味着我们不必预先询问要做多少(当我们没有更多的东西时,我们就停下来)。在
您可能还需要研究从函数返回结果,而不是使用全局变量,因为这会很快与更大的脚本混淆。在
相关问题 更多 >
编程相关推荐