首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用重复项打开文件错误

使用重复项打开文件错误
EN

Stack Overflow用户
提问于 2015-04-26 22:41:28
回答 2查看 29关注 0票数 0

我有这样的代码:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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

我得到了“打印”的结果:

代码语言:javascript
复制
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

为什么我有副本?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-04-26 22:43:34

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

代码语言:javascript
复制
if not(chain in line):
    contain+=line
    print(contain)

因为您连接了contain中的每一行,所以当您打印它时,它将显示第一个句子,第一个迭代,然后是第二个迭代中的first+second语句,依此类推。因此出现了重复。

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

票数 0
EN

Stack Overflow用户

发布于 2015-04-26 22:44:16

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

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

第三次迭代也是如此。

您正在看到副本,因为您多次打印contain,并且其中包含前面的行。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29884453

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档