Python只将最后一行写入文件

时间:2015-08-09 13:37:41

标签: python google-maps python-2.7

当我打印时,我的所有文字都会被显示,但是当写入文件时,只会写入最后一步。

 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'])

仅显示最后一步

我错过了什么?

2 个答案:

答案 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')