简体   繁体   中英

Python: Editing a single line in a text file

I have a plain text HTML file and am trying to create a Python script that amends this file.

One of the lines reads:

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

I have a little Python script that goes off and grabs the co-ordinates of the International Space Station. I then want it to amend a file to add the Latitude and Longitude.

Is it possible to use RegEx and parse just that one line? I don't fancy parsing the entire file. If it is possible, which module would be best to use? and how would I point it at that line?

If I understand you correctly, you have an HTML file with the line that you wrote out above. You want to replace the (LAT,LONG) part with the actual lat and long values that your python script will find.

If that's correct, then I would recommend going ahead and writing the HTML file to a .txt file:

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)

I haven't tested this code, so let me know if it works or not!

EDIT: If the HTML file is constantly changing, then you could use the urllib module to update it. See above code.

Thanks so much for the help. This website is awesome.

I used the info provided here and did a little bit of reading. I solved the problem by using the following:

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

Thanks again

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM