簡體   English   中英

Python:在文本文件中編輯一行

[英]Python: Editing a single line in a text file

我有一個純文本HTML文件,正在嘗試創建一個修改該文件的Python腳本。

其中一行如下:

var myLatlng = new google.maps.LatLng(LAT,LONG);

我有一個小小的Python腳本,可以關閉並獲取國際空間站的坐標。 然后,我希望它修改文件以添加緯度和經度。

是否可以使用RegEx並僅分析那一行? 我不喜歡解析整個文件。 如果可能,最好使用哪個模塊? 我怎么把它指向那條線?

如果我對您的理解正確,那么您將獲得一個HTML文件,上面帶有您在上面寫的行。 您想將(LAT,LONG)部分替換為您的python腳本將找到的實際lat和long值。

如果正確,那么我建議繼續並將HTML文件寫入.txt文件:

import urllib
import time 

while True: 

    open = urllib.urlopen(the_url_where_the_html_comes_from)
    html = open.read()

    my_file = open("file.txt","w")
    my_file.write(html)
    my_file.close()

    #you don't need any fancy modules or RegEx to edit one unique line. 
    my_file = open("file.txt","r+")
    text = my_file.read()
    text.replace("LatLng(LAT,LONG)","LatLng("+lat_variable+","+long_variable+")")
    real_text = text
    my_file.close()

    #now you want the change that you made to remain in that file
    my_file = open("file.txt","w")
    my_file.write(real_text)
    my_file.close()

    #if you check "file.txt", it should have those values replaced. 

    time.sleep(However long until the html updates)

我尚未測試此代碼,所以讓我知道它是否有效!

編輯:如果HTML文件在不斷變化,則可以使用urllib模塊進行更新。 參見上面的代碼。

非常感謝幫忙。 這個網站很棒。

我使用了此處提供的信息,並做了一些閱讀。 我通過使用以下方法解決了該問題:

#Open the html file for writing
o = open("index.html","w")
#Open the html template file, replace the variables in the code.  
line in open("template"):
line = line.replace("$LAT",lat)
line = line.replace("$LON",lon)
#Write the variables to the index.html file
o.write(line + "\n")
#Close the file
o.close()

再次感謝

暫無
暫無

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

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