3 回答
TA贡献1868条经验 获得超4个赞
Python 2
with open("datafile") as myfile:
head = [next(myfile) for x in xrange(N)]
print head
Python 3
with open("datafile") as myfile:
head = [next(myfile) for x in range(N)]
print(head)
这是另一种方式(Python 2和3)
from itertools import islice
with open("datafile") as myfile:
head = list(islice(myfile, N))
print head
TA贡献1725条经验 获得超7个赞
N = 10
file = open("file.txt", "a")#the a opens it in append mode
for i in range(N):
line = file.next().strip()
print line
file.close()
TA贡献1936条经验 获得超6个赞
如果您想快速阅读第一行而又不关心性能,则可以使用.readlines()返回列表对象然后对列表进行切片的方法。
例如前5行:
with open("pathofmyfileandfileandname") as myfile:
firstNlines=myfile.readlines()[0:5] #put here the interval you want
注意:整个文件都是读取的,因此从性能的角度来看并不是最好的,但是它易于使用,编写速度快且易于记忆,因此,如果您只想执行一次一次性计算,将非常方便
print firstNlines
添加回答
举报