简体   繁体   English

Python:在文本文件中编辑一行

[英]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. 我有一个纯文本HTML文件,正在尝试创建一个修改该文件的Python脚本。

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. 我有一个小小的Python脚本,可以关闭并获取国际空间站的坐标。 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? 是否可以使用RegEx并仅分析那一行? 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. 如果我对您的理解正确,那么您将获得一个HTML文件,上面带有您在上面写的行。 You want to replace the (LAT,LONG) part with the actual lat and long values that your python script will find. 您想将(LAT,LONG)部分替换为您的python脚本将找到的实际lat和long值。

If that's correct, then I would recommend going ahead and writing the HTML file to a .txt file: 如果正确,那么我建议继续并将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)

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. 编辑:如果HTML文件在不断变化,则可以使用urllib模块进行更新。 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 再次感谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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