【问题标题】:How to interact with notepad document correctly in python?如何在python中正确与记事本文档交互?
【发布时间】:2014-01-01 03:15:44
【问题描述】:

我创建了一个名为“connections.txt”的记事本文本文档。我需要在其中包含一些初始信息,几行只是 URL。每个 URL 都有自己的行。我手动把它放进去。然后在我的程序中,我有一个函数可以检查文件中是否存在 URL:

def checkfile(string):
    datafile = file(f)
    for line in datafile:
        if string in line:
            return True
    return False

其中 f 在程序开头声明:

f = "D:\connections.txt"

然后我尝试像这样写入文档:

file = open(f, "w")
if checkfile(user) == False:
    usernames.append(user)
    file.write("\n")
    file.write(user)
file.close()

但它并没有真正正常工作..我不确定出了什么问题..我做错了吗?

我希望记事本文档中的信息在程序运行过程中保留在那里。我希望它建立起来。

谢谢。

编辑:我发现了一些错误......它需要是file = f,而不是datafile = file(f) 但问题是......每次我重新运行程序时它都会清除文本文档。

f = "D:\connections.txt"
usernames = []

def checkfile(string):
    file = f
    for line in file:
        if string in line:
            return True
            print "True"
    return False
    print "False"

file = open(f, "w")
user = "aasdf"
if checkfile(user) == False:
    usernames.append(user)
    file.write("\n")
    file.write(user)
file.close()

【问题讨论】:

  • 让我再运行一次..
  • 大声笑——我以前从未听说有人将纯文本文件称为“记事本文档”... ^_^ 无论如何,我敢打赌它与文件路径中的反斜杠有关。看看this related question
  • 如果您想追加到文件而不是每次都覆盖它,请参阅this related question
  • 哇,我的代码完全搞砸了......
  • 好的,它现在可以工作了,但它永远不会打印真假!不是我需要它......只是看起来很奇怪

标签: python file-io


【解决方案1】:

我错误地使用了file 命令...这是有效的代码。

f = "D:\connections.txt"
usernames = []

def checkfile(string):
    datafile = file(f)
    for line in datafile:
        if string in line:
            print "True"
            return True
    print "False"
    return False 

user = "asdf"
if checkfile(user) == False:
    usernames.append(user)
    with open(f, "a") as myfile:
        myfile.write("\n")
        myfile.write(user)

【讨论】:

    【解决方案2】:

    检查特定 URL 的代码没问题! 如果问题不是擦除所有内容: 要写入文档而不删除所有内容,您必须使用 .seek() 方法:

    file = open("D:\connections.txt", "w")
    # The .seek() method sets the cursor to the wanted position
    # seek(offset, [whence]) where:
    # offset = 2 is relative to the end of file
    # read more here: http://docs.python.org/2/library/stdtypes.html?highlight=seek#file.seek
    file.seek(2)
    file.write("*The URL you want to write*")
    

    在您的代码上实现将类似于:

    def checkfile(URL):
    # your own function as it is...
    
    if checkfile(URL) == False:
        file = open("D:\connections.txt", "w")
        file.seek(2)
        file.write(URL)
        file.close()
    

    【讨论】:

    • 谢谢..但这不是重点...我正在检查文本文档中是否有特定的网址
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 2021-04-14
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    相关资源
    最近更新 更多