失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python编写程序输出诗句 我如何让python从包含一首诗的文件中仅读取其他所有行...

python编写程序输出诗句 我如何让python从包含一首诗的文件中仅读取其他所有行...

时间:2023-01-15 14:57:25

相关推荐

python编写程序输出诗句 我如何让python从包含一首诗的文件中仅读取其他所有行...

I know the code for reading every line is

f=open ('poem.txt','r')

for line in f:

print line

how do you have python read only even-numbered lines from the original file. Assuming 1-based numbering of lines.

解决方案

There are quite a few different ways, here a simple one

with open('poem.txt', 'r') as f:

count = 0

for line in f:

count+=1

if count % 2 == 0: #this is the remainder operator

print(line)

This also might be a little nicer, saving the lines for declaring and incrementing the count:

with open('poem.txt', 'r') as f:

for count, line in enumerate(f, start=1):

if count % 2 == 0:

print(line)

如果觉得《python编写程序输出诗句 我如何让python从包含一首诗的文件中仅读取其他所有行...》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。