当我打印时,我的所有文字都会被显示,但是当写入文件时,只会写入最后一步。
import json, urllib
from urllib import urlencode
import googlemaps
start = "Bridgewater, Sa, Australia"
finish = "Stirling, SA, Australia"
url = 'http://maps.googleapis.com/maps/api/directions/json?%s' % urlencode((
('origin', start),
('destination', finish)
))
ur = urllib.urlopen(url)
result = json.load(ur)
for i in range (0, len (result['routes'][0]['legs'][0]['steps'])):
j = result['routes'][0]['legs'][0]['steps'][i]['html_instructions']
print j
output = open("output.html", "w")
output.write(j)
output.close()
我也试过
output.write("%s\n" % j)
我收到错误并
output.write(result['routes'][0]['legs'][0]['steps'][i]['html_instructions'])
仅显示最后一步
我错过了什么?
答案 0 :(得分:3)
这是因为您正在写入for循环外的文件,因此j
仅包含最后一次迭代的值,因此您只将最后一行写入该文件。
您应该在循环之前打开文件,并在循环内写入文件,也可以使用with
语句打开文件,以便自动处理关闭。示例 -
with open("output.html", "w") as output:
for i in range (0, len (result['routes'][0]['legs'][0]['steps'])):
j = result['routes'][0]['legs'][0]['steps'][i]['html_instructions']
print j
output.write(j + '\n')
答案 1 :(得分:0)
你只写最后一行,因为,写在你的for循环之外:
with open("output.html", "w") as output:
for step in result['routes'][0]['legs'][0]['steps']:
print step['html_instructions']
output.write(step['html_instructions']+'\n')