我们有一个很大的原始数据文件,我们想把它修剪成指定的大小。
如何在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。;)
我所做的就是用熊猫形来称呼N行。我认为性能不是最好的,但是举个例子,如果N=1000:
import pandas as pd
yourfile = pd.read_csv('path/to/your/file.csv',nrows=1000)
这适用于Python 2和3:
from itertools import islice
with open('/tmp/filename.txt') as inf:
for line in islice(inf, N, N+M):
print(line)
使用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)
这里有另一个不错的解决方案与列表理解:
file = open('file.txt', 'r')
lines = [next(file) for x in range(3)] # first 3 lines will be in this list
file.close()