[英]Python for loop through array creating JSON file
我有創建json對象文件的代碼,並將其制作成漂亮的新文件。 在這里找到:
# Creates a storage file for the
with open('placeInfo.json', 'w') as outfile:
json.dump(api.trends_place(id=location_array[1]), outfile)
with open('placeInfo.json', 'r') as handle:
parsed = json.load(handle)
prettyFile = json.dumps(parsed, indent=4, sort_keys=True)
pfFile = json.loads(prettyFile) #use for indexing
print prettyFile
x = 'number1'
f = open(x + 'newFile.json', 'w')
f.write(prettyFile)
我想做的是遍歷一個數組(0-17個元素),並使用id=location_array[x]
索引數組中的每個位置。
x = 0
while x < len(location_array):
with open('placeInfo.json', 'w') as outfile:
json.dump(api.trends_place(id=location_array[x]), outfile)
with open('placeInfo.json', 'r') as handle:
parsed = json.load(handle)
pretty_file = json.dumps(parsed, indent = 4, sort_keys = True)
print pretty_file
f = open(x + 'newFile.json', 'w')
f.write(pretty_file)
x += 1
第一個代碼塊返回一個有效的新json文件,但是while循環甚至無法識別一個json文件。 我在哪里錯了? 還可以建議簡化此代碼嗎?
首先,您不應為此使用while循環。
好的方法是:
for x, value in enumerate(location_array):
# Then you can access to the value you want with
print value
# Instead of
print location_array[x]
# And you still can access to the index
print x
另外,您應該使用with
語法打開所有文件。 在您的示例中,您忘記了關閉最后打開的文件(xnewFile.json)。 這不好。 使用with
語法,您不必擔心。
所以我認為這應該工作:
for x, location in enumerate(location_array):
with open(x + 'newFile.json', 'w') as outfile:
parsed = api.trends_place(id=location)
json.dumps(parsed, outfile, indent=4, sort_keys=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.