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

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


当前回答

我想通过读取整个文件来处理小于n行的文件

def head(filename: str, n: int):
    try:
        with open(filename) as f:
            head_lines = [next(f).rstrip() for x in range(n)]
    except StopIteration:
        with open(filename) as f:
            head_lines = f.read().splitlines()
    return head_lines

这要归功于约翰·拉·鲁伊和伊莲·伊利耶夫。使用异常句柄函数以获得最佳性能

修改1:感谢FrankM的反馈,处理文件存在和读取权限我们可以进一步增加

import errno
import os

def head(filename: str, n: int):
    if not os.path.isfile(filename):
        raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), filename)  
    if not os.access(filename, os.R_OK):
        raise PermissionError(errno.EACCES, os.strerror(errno.EACCES), filename)     
   
    try:
        with open(filename) as f:
            head_lines = [next(f).rstrip() for x in range(n)]
    except StopIteration:
        with open(filename) as f:
            head_lines = f.read().splitlines()
    return head_lines

您可以使用第二个版本,也可以使用第一个版本,稍后再处理文件异常。从性能的角度来看,检查是快速的,而且大部分是免费的

其他回答

这对我很有效

f = open("history_export.csv", "r")
line= 5
for x in range(line):
    a = f.readline()
    print(a)

从Python 2.6开始,您可以利用IO基类中更复杂的函数。所以上面评分最高的答案可以改写为:

    with open("datafile") as myfile:
       head = myfile.readlines(N)
    print head

(你不必担心你的文件少于N行,因为没有StopIteration异常抛出。)

#!/usr/bin/python

import subprocess

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

output, err = p.communicate()

print  output

这个方法对我很有效

对于前5行,简单地做:

N=5
with open("data_file", "r") as file:
    for i in range(N):
       print file.next()
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)