我们有一个很大的原始数据文件,我们想把它修剪成指定的大小。
如何在python中获取文本文件的前N行?所使用的操作系统对实现有任何影响吗?
我们有一个很大的原始数据文件,我们想把它修剪成指定的大小。
如何在python中获取文本文件的前N行?所使用的操作系统对实现有任何影响吗?
当前回答
如果你想快速读取第一行并且不关心性能,你可以使用.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]。
其他回答
没有特定的方法来读取文件对象暴露的行数。
我想最简单的方法是:
lines =[]
with open(file_name) as f:
lines.extend(f.readline() for i in xrange(N))
fname = input("Enter file name: ")
num_lines = 0
with open(fname, 'r') as f: #lines count
for line in f:
num_lines += 1
num_lines_input = int (input("Enter line numbers: "))
if num_lines_input <= num_lines:
f = open(fname, "r")
for x in range(num_lines_input):
a = f.readline()
print(a)
else:
f = open(fname, "r")
for x in range(num_lines_input):
a = f.readline()
print(a)
print("Don't have", num_lines_input, " lines print as much as you can")
print("Total lines in the text",num_lines)
我自己最方便的方法:
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。;)
我所做的就是用熊猫形来称呼N行。我认为性能不是最好的,但是举个例子,如果N=1000:
import pandas as pd
yourfile = pd.read_csv('path/to/your/file.csv',nrows=1000)
Python 3:
with open("datafile") as myfile:
head = [next(myfile) for x in range(N)]
print(head)
Python 2:
with open("datafile") as myfile:
head = [next(myfile) for x in xrange(N)]
print head
下面是另一种方法(Python 2和3都是):
from itertools import islice
with open("datafile") as myfile:
head = list(islice(myfile, N))
print(head)