如何在python中正确地与记事本文档交互?

时间:2014-01-01 03:15:45

标签: python file-io

我创建了一个名为“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()

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

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

感谢。

编辑:我发现了一些错误......它必须是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()

2 个答案:

答案 0 :(得分:0)

我正在使用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)

答案 1 :(得分:0)

检查特定网址的代码是可以的! 如果问题没有消除一切: 要在不删除所有内容的情况下写入文档,必须使用.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()