2013-03-13 55 views
0

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

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

这实质上是比较整个线段。 有没有办法做到这一点在Python中不使用正则表达式?

+0

为什么你认为你应该使用正则表达式?将文件的内容加载为字符串,并尝试在第二个字符串中找到第一个字符串。 – khachik 2013-03-13 11:58:23

+0

ya.you r right。谢谢你给我一个更简单的方法。 – 2013-03-13 12:33:20

回答

2
src = open('source').read() 
if src not in open('dest').read(): 
    with open('dest', 'a') as dst: 
     dst.write(src) 
+0

非常感谢 – 2013-03-13 12:39:52

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) 
+0

嗨,我试过你的方法。它会抛出一个错误文件“IOError:File not open for writing”。请帮助 – 2013-03-13 12:25:33

+0

是的,我忘了模式。补充说明,仅仅是为了它。 – fog 2013-03-13 14:30:50