字符串比较不识别匹配

string comparison not recognizing match

我在 'origFile' 中有一个 url 列表,这些 url 将被扩充并写入 'readyFile'。我只想将 url 添加到 'readyFile',前提是它们不在 'readyFile' 中。

with open('bpBlacklist.txt', 'r') as origFile, open('bpBlacklistReady','r+') as readyFile :
    for line in origFile:       
        orig_string = line.strip()
        if orig_string in readyFile.read():
            None
        else: 
            readyFile.write( "'" + orig_string + "'," + '\n' )

    origFile.close()    
    readyFile.close()

现在,每次我 运行 它都会将整个列表重写为 'readyFile'。我尝试将 "'+ str + '" 扩充移到 if 语句之外,但问题仍然存在。

通过写入 readyFile.write(...),您的下一个 readyFile.read() 调用将被覆盖。您应该在 with 语句之后立即将 readyFile 内容保存到变量中:

with open('bpBlacklist.txt', 'r') as origFile, open('bpBlacklistReady','r+') as readyFile :
     readyFileContent = readyFile.read()

您的条件不符合您的预期,因为 read() 方法会将整个文件 return 作为字符串。您需要检查可迭代的 url 之间的成员资格。

而不是遍历文件并检查所有 url 的成员资格,您可以使用 set.difference() 函数找到差异,然后编写额外的 urls:

with open('bpBlacklist.txt', 'r') as origFile, open('bpBlacklistReady','r+') as readyFile :
    current = set(origFile)
    diffs = current.difference(readyFile.readlines())
    for url in diffs:
        readyFile.write(url + '\n')