打开文件错误与重复

opening file error with duplicates

我有这个代码:

chain = '>'
contain=''

file = raw_input('Enter your filename : ')


fileName = open(file,'r')
for line in fileName:
 if chain in line :
  pass
   
 if not(chain in line):
  contain+=line
  print contain
  

fileName.close()

和这个 file.txt :

Python supports multiple programming paradigms, including object-oriented, imperative and functional programming. 
It features a dynamic type system and automatic memory management.
He has a large and comprehensive standard library

我得到了 "print" 的结果:

Python supports multiple programming paradigms, including object-oriented, imperative and functional programming. 

Python supports multiple programming paradigms, including object-oriented, imperative and functional programming. 
It features a dynamic type system and automatic memory management.

Python supports multiple programming paradigms, including object-oriented, imperative and functional programming. 
It features a dynamic type system and automatic memory management.
He has a large and comprehensive standard library

为什么我有重复的?

在循环的每次迭代中,当:

if not(chain in line):
    contain+=line
    print(contain)

因为您连接了 contain 中的每一行,所以当您打印它时,它会显示第一个句子,从第一次迭代开始,然后是第二次迭代中的第一个+第二个句子,依此类推。因此重复。

print(contain) 替换为 print(line) 将不重复地打印这些行。

第一次迭代后,将文件的第一行添加到 contain,然后打印它。

第二次迭代后,将文件的第二行添加到 contain,其中仍然包含第一行,然后打印它。

第三次迭代也是如此。

您看到了重复项,因为您打印了 contain 多次,并且其中包含前面的行。