如何在python中写入文件时是否已存在行?

时间:2014-08-02 08:48:26

标签: python python-2.7

我有包含

行的file1.txt
list 0
list 1
line 1

在file2.txt中,我只想在file2.txt

中不存在该行时写入

我的代码:

fo=open("file1.txt","r")
fin=open("file2.txt","a")
lines=fo.readlines()

for line in lines:
    if "list" in line:
       fin.write(line)

for line in lines:
    if "li" in line:
       fin.write(line)

输出:正在打印两次。如果重复相同的行,我只想写一次。

list 0 
list 1    
list 0    
list 1    
line 1

我的输出应该是

list 0   
list 1    
line 1

4 个答案:

答案 0 :(得分:2)

我建议首先阅读file2.txt的所有行并将它们放入合适的数据结构(即Set)。 然后在追加模式下重新打开file2.txt,遍历file1.txt的所有行并只写入不在集合中的这些行(这里,in运算符很方便......)

with open("file2.txt", "r") as f2:
  lineset = set(f2)

with open("file2.txt", "a") as f2:
  with open("file1.txt", "r") as f1:
    for line in f1:
      if not line in lineset:
        d2.write(line)

答案 1 :(得分:1)

这将读取file2中的所有行,如果尚未存在,则只写一行到file2。它还将使用python中优秀的“with”语句自动关闭文件。 :)

with open("file1.txt","r") as file1, open("file2.txt", "w+") as file2:
    lines2 = file2.readlines()
    for line in file1:
        if line not in lines2:
            file2.write(line)

如果你想使用列表迭代,相同的代码只有2行,但我更喜欢第一个版本的可读性。

with open("file1.txt", "r") as file1, open("file2.txt", "w+") as file2:
    [file2.write(line) for line in file1 if line not in file2.readlines()]

答案 2 :(得分:1)

使用集合来跟踪file2.txt文件中的行集合。

fo=open("file1.txt","r")
fin=open("file2.txt","a")
lines=fo.readlines()
# Rewing the file so that we can read it's contents.
fin.seek(0)
existing_lines = set(fin)

for line in lines:
    if line not in existing_lines:
       fin.write(line)
       existing_lines.add(line)

答案 3 :(得分:-1)

您可能希望执行以下操作:

fo=open("file1.txt","r")
fin=open("file2.txt","a")
linesOut=fo.readlines()
linesIn=fin.readlines()

for lineOut in linesOut:

    #check each line in linesIn to see if it contains lineOut
    writeLine=True
    for lineIn in linesIn:
        if lineOut==lineIn:
            writeLine=False

    #if not add it
    if writeLine:
        fin.write(lineOut)