我们有一个很大的原始数据文件,我们想把它修剪成指定的大小。
如何在python中获取文本文件的前N行?所使用的操作系统对实现有任何影响吗?
我们有一个很大的原始数据文件,我们想把它修剪成指定的大小。
如何在python中获取文本文件的前N行?所使用的操作系统对实现有任何影响吗?
当前回答
我所做的就是用熊猫形来称呼N行。我认为性能不是最好的,但是举个例子,如果N=1000:
import pandas as pd
yourfile = pd.read_csv('path/to/your/file.csv',nrows=1000)
其他回答
我自己最方便的方法:
LINE_COUNT = 3
print [s for (i, s) in enumerate(open('test.txt')) if i < LINE_COUNT]
基于列表理解的解决方案 函数open()支持迭代接口。enumerate()包含open()和return元组(index, item),然后检查是否在可接受的范围内(如果i < LINE_COUNT),然后简单地打印结果。
欣赏Python。;)
基于gnibbler的投票结果(2009年11月20日0:27):这个类将head()和tail()方法添加到文件对象。
class File(file):
def head(self, lines_2find=1):
self.seek(0) #Rewind file
return [self.next() for x in xrange(lines_2find)]
def tail(self, lines_2find=1):
self.seek(0, 2) #go to end of file
bytes_in_file = self.tell()
lines_found, total_bytes_scanned = 0, 0
while (lines_2find+1 > lines_found and
bytes_in_file > total_bytes_scanned):
byte_block = min(1024, bytes_in_file-total_bytes_scanned)
self.seek(-(byte_block+total_bytes_scanned), 2)
total_bytes_scanned += byte_block
lines_found += self.read(1024).count('\n')
self.seek(-total_bytes_scanned, 2)
line_list = list(self.readlines())
return line_list[-lines_2find:]
用法:
f = File('path/to/file', 'r')
f.head(3)
f.tail(3)
N = 10
with open("file.txt", "a") as file: # the a opens it in append mode
for i in range(N):
line = next(file).strip()
print(line)
如果你想要一些明显(不需要在手册中查找深奥的东西)不需要导入就可以工作的东西,请尝试/except,并且可以在相当大范围的Python 2上工作。X版本(2.2至2.6):
def headn(file_name, n):
"""Like *x head -N command"""
result = []
nlines = 0
assert n >= 1
for line in open(file_name):
result.append(line)
nlines += 1
if nlines >= n:
break
return result
if __name__ == "__main__":
import sys
rval = headn(sys.argv[1], int(sys.argv[2]))
print rval
print len(rval)
对于前5行,简单地做:
N=5
with open("data_file", "r") as file:
for i in range(N):
print file.next()