打开文件错误,重复

时间:2015-04-26 22:41:29

标签: python 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

为什么我有重复项?

2 个答案:

答案 0 :(得分:0)

在循环的每次迭代中,时间:

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

因为你连接contain中的每一行,当你打印它时,它会显示第一次迭代,第一次迭代,第二次迭代中的第一个+第二个句子,依此类推。因此重复。

print(contain)替换print(line)将打印不重复的行。

答案 1 :(得分:0)

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

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

第三次迭代也是如此。

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