我知道读取每一行的代码是
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