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