Python Only last line is written to file
Question: When I do print all my text is shown but when written to file only the last
step is written.

    
    
     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()
    

I have also tried

    
    
       output.write("%s\n" %  j)
    

I get an error and

    
    
       output.write(result['routes'][0]['legs'][0]['steps'][i]['html_instructions'])
    

Shows only last step

What am I missing?


Answer: That is because you are writing to file outside the for loop, so `j` contains
value only for the last iteration and hence you only write the last line to
the file.

You should instead open the file before the loop, and write to file inside the
loop , also would be good to use `with` statement to open the file , so that
closing is automatically handled. Example -

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

