在python中写入没有冗余行的文件

  • 本文关键字:冗余 文件 python python
  • 更新时间 :
  • 英文 :


我正在编写python脚本,从输入文件中读取行,并将唯一的行(如果同一行尚未在输出文件中)写入输出文件。不知何故,我的脚本总是将输入文件的第一行附加到输出文件,即使同一行已经在输出文件中。我不明白为什么会这样。有人知道为什么和如何解决这个问题吗?谢谢你,

import  os
input_file= 'input.txt'
output_file = 'output.txt'
fo = open(output_file, 'a+')
flag = False
with open(input_file, 'r') as fi:
    for line1 in fi:
       print line1
       for line2 in fo:
           print line2
           if line2 == line1:
               flag = True
               print('Found Match!!')
               break
       if flag == False:
           fo.write(line1)
       elif flag == True:
           flag == False
       fo.seek(0)
    fo.close()
    fi.close()

以追加模式打开文件时,文件对象位置位于文件末尾。所以第一次,当它到达for line2 in fo:时,fo中没有更多的行,所以这个块被跳过,flag仍然为真,所以第一行被写入输出文件。在此之后,执行fo.seek(0),这样您将检查整个文件中的后续行。

kmachinnis的答案是正确的,为什么你的代码不能工作;你需要使用模式'r+'而不是'a+',否则把fo.seek(0)放在for循环的开始而不是结束。

也就是说,有一种比读取整个输出文件中的每一行更好的方法。
def ensure_file_ends_with_newline(handle):
    position = handle.tell()
    handle.seek(-1, 2)
    handle_end = handle.read(1)
    if handle_end != 'n':
        handle.write('n')
    handle.seek(position)

input_filepath = 'input.txt'
output_filepath = 'output.txt'
with open(input_file, 'r') as infile, open(output_file, 'r+') as outfile:
    ensure_file_ends_with_newline(outfile)
    written = set(outfile)
    for line in infile:
        if line not in written:
            outfile.write(line)
            written.add(line)

您的标志从未设置为False。

flag == True是一个等式

flag = True是赋值。

试试后者

import  os
input_file= 'input.txt'
output_file = 'output.txt'
fo = open(output_file, 'a+')
flag = False
with open(input_file, 'r') as fi:
    for line1 in fi:
       #print line1
       for line2 in fo:
           #print line2
           if line2 == line1:
               flag = True
               print('Found Match!!')
               print (line1,line2)
               break
       if flag == False:
           fo.write(line1)
       elif flag == True:
           flag = False
       fo.seek(0)

最新更新