簡體   English   中英

Python僅將最后一行寫入文件

[英]Python Only last line is written to file

當我執行打印時,將顯示所有文本,但是當寫入文件時,僅寫入最后一步。

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

僅顯示最后一步

我想念什么?

那是因為您正在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')

您只寫最后一行,因為寫操作在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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM