如果此字符串不包含,则将字符串写入文件

时间:2015-02-20 10:48:53

标签: python

我有一个Python函数,它接受一个字符串并将其写入文本文件。我改变了,所以如果它已经存在,它就不会写一个字符串,但它似乎根本不起作用。

def log_folder(folder):
    fname = 'folder.log'
    fname_exists = os.path.isfile(fname)

    if not fname_exists:
       with open(fname,'a+') as outfile:
            outfile.write(folder+'\n')
    else:
         with open(fname,'r+') as inf:
              if folder not in inf.readlines():
                 inf.write(folder+'\n')

文件中的预期结果是:

home/cyberbemon/20150203_220759+0000
home/cyberbemon/20150203_220759+0012
home/cyberbemon/20150203_220858+0000

我得到的是:

/home/cyberbemon/20150203_220759+0000
/home/cyberbemon/20150203_220759+0012
/home/cyberbemon/20150203_220858+0000
/home/cyberbemon/20150203_220759+0000
/home/cyberbemon/20150203_220759+0012
/home/cyberbemon/20150203_220858+0000

正如您所看到的,即使它们存在于文件中,它们仍在编写中。

1 个答案:

答案 0 :(得分:2)

您正在检查文件的任何行是否等于文件夹。 但是你要存储文件夹+' \'在每一行。

您应该更改此行:

if folder not in inf.readlines():

要:

if folder+'\n' not in inf.readlines():