我们有一个很大的原始数据文件,我们想把它修剪成指定的大小。

如何在python中获取文本文件的前N行?所使用的操作系统对实现有任何影响吗?


当前回答

没有特定的方法来读取文件对象暴露的行数。

我想最简单的方法是:

lines =[]
with open(file_name) as f:
    lines.extend(f.readline() for i in xrange(N))

其他回答

这对我很有效

f = open("history_export.csv", "r")
line= 5
for x in range(line):
    a = f.readline()
    print(a)
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)
#!/usr/bin/python

import subprocess

p = subprocess.Popen(["tail", "-n 3", "passlist"], stdout=subprocess.PIPE)

output, err = p.communicate()

print  output

这个方法对我很有效

使用list(file_data)将CSV文件对象转换为列表

import csv;
with open('your_csv_file.csv') as file_obj:
    file_data = csv.reader(file_obj);
    file_list = list(file_data)
    for row in file_list[:4]:
        print(row)

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

例如,前5行:

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

注意:整个文件是读取的,所以不是最好的从性能的角度来看,但它 是易于使用,快速编写和易于记忆,所以如果你只是想执行 一些一次性计算非常方便

print firstNlines

与其他答案相比,一个优点是可以轻松地选择行范围,例如跳过前10行[10:30]或最后10行[:-10]或只选择偶数行[::2]。