0

在检查源文件中的所有行(作为一个组)是否已经存在于目标文件中之后,我有一个包含需要附加到目标文件的内容的源文件。

如果它已经在目标文件中找到,我不应该再次追加,因为这会复制目标文件中的内容。

这实质上是在将行块作为一个整体进行比较。有没有办法在不使用正则表达式的情况下在 python 中做到这一点?

4

2 回答 2

2
src = open('source').read()
if src not in open('dest').read():
    with open('dest', 'a') as dst:
        dst.write(src)
于 2013-03-13T12:19:35.187 回答
0

如果您可以将整个文件作为单个字符串加载到内存中,那么您可以简单地使用count

import os

f = open("the_file_name", 'r+')
s1 = "the block of text\nwith newlines!\nyou will search in the file"
s2 = f.read() # s2 now has the whole file
if s2.count(s1) > 0:
    # seek to end and append s1
    f.seek(0, os.SEEK_END)
    f.write(s1)
于 2013-03-13T12:01:38.773 回答