在python中读取文件的前N行

2024-04-25 12:03:54 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

Python2

with open("datafile") as myfile:
    head = [next(myfile) for x in xrange(N)]
print head

Python3

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

如果希望快速读取第一行,而不关心性能,可以使用.readlines()返回list对象,然后对列表进行切片。

例如,对于前5行:

with open("pathofmyfileandfileandname") as myfile:
    firstNlines=myfile.readlines()[0:5] #put here the interval you want

Note: the whole file is read so is not the best from the performance point of view but it is easy to use, fast to write and easy to remember so if you want just perform some one-time calculation is very convenient

print firstNlines
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()

相关问题 更多 >

    热门问题