我们有一个很大的原始数据文件,我们想把它修剪成指定的大小。
如何在python中获取文本文件的前N行?所使用的操作系统对实现有任何影响吗?
我们有一个很大的原始数据文件,我们想把它修剪成指定的大小。
如何在python中获取文本文件的前N行?所使用的操作系统对实现有任何影响吗?
当前回答
如果你想要一些明显(不需要在手册中查找深奥的东西)不需要导入就可以工作的东西,请尝试/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)
其他回答
使用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)
这适用于Python 2和3:
from itertools import islice
with open('/tmp/filename.txt') as inf:
for line in islice(inf, N, N+M):
print(line)
这里有另一个不错的解决方案与列表理解:
file = open('file.txt', 'r')
lines = [next(file) for x in range(3)] # first 3 lines will be in this list
file.close()
从Python 2.6开始,您可以利用IO基类中更复杂的函数。所以上面评分最高的答案可以改写为:
with open("datafile") as myfile:
head = myfile.readlines(N)
print head
(你不必担心你的文件少于N行,因为没有StopIteration异常抛出。)
没有特定的方法来读取文件对象暴露的行数。
我想最简单的方法是:
lines =[]
with open(file_name) as f:
lines.extend(f.readline() for i in xrange(N))