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)


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部