本问题已经有最佳答案,请猛点这里访问。

我有一个python脚本,它需要读取一个非常大的文本文件的一部分,从n行开始,到n+x结束。我不想使用"open('file')",因为这样会把整个东西写到内存中,这既需要太长的时间,又浪费了太多的内存。我的脚本在一台Unix机器上运行,因此我目前使用本地的head和tail函数,即:

1section = subprocess.check_output('tail -n-N {filePath} | head -n X')

但感觉必须有一个更聪明的方法去做。有没有一种方法可以在不打开整个文件的情况下,在python中获取文本文件的n到n+x行?

谢谢!

"我不想使用"open('file')",因为这样会将整个内容写入内存,这既需要太长时间,又浪费太多内存。"这不是open所做的;使用它。

python的islice()非常适合这样做:

1

2

3

4

5

6

7

8from itertools import islice

N = 2

X = 5

with open('large_file.txt') as f_input:

for row in islice(f_input, N-1, N+X):

print row.strip()

这跳过所有初始行,只返回您感兴趣的行。

您的问题的答案位于这里:如何在python中逐行读取大文件

1

2

3with open(...) as f:

for line in f:

The with statement handles opening and closing the file, including if

an exception is raised in the inner block. The for line in f treats

the file object f as an iterable, which automatically uses buffered IO

and memory management so you don't have to worry about large files.

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐