reading the first N lines in a file without opening it (Python)
本问题已经有最佳答案,请猛点这里访问。
我有一个python脚本,它需要读取一个非常大的文本文件的一部分,从n行开始,到n+x结束。我不想使用"open('file')",因为这样会把整个东西写到内存中,这既需要太长的时间,又浪费了太多的内存。我的脚本在一台Unix机器上运行,因此我目前使用本地的head和tail函数,即:
1 | section = subprocess.check_output('tail -n-N {filePath} | head -n X') |
但感觉必须有一个更聪明的方法去做。有没有一种方法可以在不打开整个文件的情况下,在python中获取文本文件的n到n+x行?
谢谢!
python的
1 2 3 4 5 6 7 8 | from 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 3 | with open(...) as f: for line in f: <do something with line> |
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.