首页 > 解决方案 > 检查一个字符串是否在一个文件中,如果它没有附加它

问题描述

所以我试图让程序检查一个字符串是否在文件中,如果它不只是将它附加到末尾(在一个新行中),如果不是,它什么也不做。

我已经尝试过 w+ 但它只是覆盖整个文件而不是附加它,如果我尝试 a+ 它只是附加而不检查,即使字符串在文件中。所以我的问题是:

如何设法检查字符串是否已经在文件中,如果没有,请附加它。

这是一个示例代码:

with open("testfile.txt", "a+") as testfile:
    word = "test"
    inhalt = testfile.read ()
    if word not in inhalt:
        testfile.write ("something"+ "\n")
    else:
        pass

标签: pythonfile

解决方案


我更喜欢这样的任务分两步完成。见下文:

with open("testfile.txt") as testfile:
    word = "test"
    inhalt = testfile.read ()
if word not in inhalt:
    with open("testfile.txt", 'a') as testfile:
        testfile.write(word+ "\n")

推荐阅读