我知道读取每一行代码的方法是:
f=open ('poem.txt','r')
for line in f:
print line
如何让Python只读取原始文件中的偶数行。假设行号从1开始计数。
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)
with open('poem.txt', 'r') as f:
for count, line in enumerate(f, start=1):
if count % 2 == 0:
print(line)
以下翻译自 Nick Bastin的评论:
with open('poem.txt', 'r') as f:
for count, line in enumerate(f, start=1):
if count % 2 == 0:
print line
float(n) for n in line.split("\t")
。 - wjandrea
with open('poem.txt', 'r') as f:
就是你想要的(这样如果你崩溃等情况发生时,文件会被正确关闭)。 - Nick Bastinenumerate
:for count, line in enumerate(f, start=1): if count % 2 == 0...
这样可以避免创建或自己增加计数器。 :-) - Nick Bastin