【问题标题】:python - history filepython - 历史文件
【发布时间】:2016-11-01 01:15:58
【问题描述】:

我有一个项目

我正在制作一个文本浏览器,我需要帮助

我有一个历史文件,每个 url 和时间都放在历史文件中,例如:

www.youtube.com 2016-06-29 13:47:15.986000

www.youtube.com 2016-06-29 13:47:22.416000

www.youtube.com 2016-06-29 13:47:31.962000

www.youtube.com 2016-06-29 13:47:40.713000

www.youtube.com 2016-06-29 13:47:49.193000

我需要创建一个 remove 函数来获取一个 url,并删除所有行

(以“\n”分隔的行)

这是历史文件的代码:

def Update_history(url):
    thistime = str(datetime.datetime.now())
    urlat = url + " " + thistime
    history = open("somthing.txt" , "w")
    history.write(urlat)
    history.write("\n")

请帮帮我,这是为了明天!

【问题讨论】:

  • 要求人们帮助你,因为你等到最后一分钟才会产生反对票。相反,摆脱问题的最后一部分并解释为什么您的删除方法不成功。您具体遇到了什么问题以及您尝试了哪些代码? StackOverflow 不是代码编写服务。

标签: python python-2.7 file


【解决方案1】:

如果你想从文件中删除这行,试试这个:

import os

def removeUrl(url):
    url_file = "url.txt"
    fileIn = open(url_file, 'r')
    fileOut = open("temp.txt", 'w')
    for line in fileIn:
        if url not in line:
            fileOut.write(line)
    fileIn.close()
    fileOut.close()

    os.remove(url_file)
    os.rename("temp.txt", url_file)

removeUrl("www.youtube.com")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 2013-10-07
    • 2012-06-18
    • 2011-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多