如何读取文件的前 N 行?

2025-02-10 08:57:00
admin
原创
49
摘要:问题描述:我们有一个很大的原始数据文件,我们想将其修剪到指定的大小。如何在 Python 中获取文本文件的前 N ​​行?所使用的操作系统会对实现产生影响吗?解决方案 1:Python 3:with open(path_to_file) as input_file: head = [next(inpu...

问题描述:

我们有一个很大的原始数据文件,我们想将其修剪到指定的大小。

如何在 Python 中获取文本文件的前 N ​​行?所使用的操作系统会对实现产生影响吗?


解决方案 1:

Python 3:

with open(path_to_file) as input_file:
    head = [next(input_file) for _ in range(lines_number)]
print(head)

Python 2:

with open(path_to_file) as input_file:
    head = [next(input_file) for _ in xrange(lines_number)]
print head

这是另一种方法(Python 2 和 Python 3):

from itertools import islice

with open(path_to_file) as input_file:
    head = list(islice(input_file, lines_number))
print(head)

解决方案 2:

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)

解决方案 3:

如果您想快速阅读第一行并且不关心性能,您可以使用.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]

解决方案 4:

我所做的是使用 调用 N 行pandas。我认为性能不是最好的,但是例如如果N=1000

import pandas as pd
yourfile = pd.read_csv('path/to/your/file.csv',nrows=1000)

解决方案 5:

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

我想最简单的方法如下:

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

解决方案 6:

最直观的两种方法是:

  1. 逐行迭代文件,然后break逐行N迭代。

  2. next()使用方法times逐行迭代文件N。(这本质上只是最佳答案的不同语法。)

以下是代码:

# Method 1:
with open("fileName", "r") as f:
    counter = 0
    for line in f:
        print line
        counter += 1
        if counter == N: break

# Method 2:
with open("fileName", "r") as f:
    for i in xrange(N):
        line = f.next()
        print line

底线是,只要您不使用readlines()enumerate将整个文件放入内存,您就有很多选择。

解决方案 7:

根据 gnibbler 最佳投票答案 (2009 年 11 月 20 日 0:27):此类向文件对象添加 head() 和 tail() 方法。

class File(file):
    def head(self, lines_2find=1):
        self.seek(0)                            #Rewind file
        return [self.next() for x in xrange(lines_2find)]

    def tail(self, lines_2find=1):  
        self.seek(0, 2)                         #go to end of file
        bytes_in_file = self.tell()             
        lines_found, total_bytes_scanned = 0, 0
        while (lines_2find+1 > lines_found and
               bytes_in_file > total_bytes_scanned): 
            byte_block = min(1024, bytes_in_file-total_bytes_scanned)
            self.seek(-(byte_block+total_bytes_scanned), 2)
            total_bytes_scanned += byte_block
            lines_found += self.read(1024).count('
')
        self.seek(-total_bytes_scanned, 2)
        line_list = list(self.readlines())
        return line_list[-lines_2find:]

用法:

f = File('path/to/file', 'r')
f.head(3)
f.tail(3)

解决方案 8:

我自己最方便的方式:

LINE_COUNT = 3
print [s for (i, s) in enumerate(open('test.txt')) if i < LINE_COUNT]

基于列表理解的解决方案
open() 函数支持迭代接口。enumerate() 覆盖 open() 并返回元组 (index, item),然后我们检查是否在可接受范围内(如果 i < LINE_COUNT),然后简单地打印结果。

享受 Python。;)

解决方案 9:

对于前 5 行,只需执行以下操作:

N=5
with open("data_file", "r") as file:
    for i in range(N):
       print file.next()

解决方案 10:

如果您想要一些显然(不需在手册中查找深奥的东西)无需 imports 和 try/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)

解决方案 11:

如果你有一个非常大的文件,并且假设你希望输出为 numpy 数组,那么使用 np.genfromtxt 将冻结你的计算机。根据我的经验,这要好得多:

def load_big_file(fname,maxrows):
'''only works for well-formed text file of space-separated doubles'''

rows = []  # unknown number of lines, so use list

with open(fname) as f:
    j=0        
    for line in f:
        if j==maxrows:
            break
        else:
            line = [float(s) for s in line.split()]
            rows.append(np.array(line, dtype = np.double))
            j+=1
return np.vstack(rows)  # convert list of vectors to array

解决方案 12:

这对我有用

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

解决方案 13:

我想通过读取整个文件来处理少于 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

感谢 John La Rooy 和 Ilian Iliev。使用带有异常处理功能的函数可获得最佳性能

修订 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

您可以选择第二个版本,也可以选择第一个版本,稍后处理文件异常。检查速度很快,而且从性能角度来看基本免费

解决方案 14:

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

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

(由于没有抛出 StopIteration 异常,因此您不必担心文件少于 N 行。)

解决方案 15:

这适用于 Python 2 和 3:

from itertools import islice

with open('/tmp/filename.txt') as inf:
    for line in islice(inf, N, N+M):
        print(line)

解决方案 16:


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)

解决方案 17:

这是另一个具有列表理解的不错的解决方案:

file = open('file.txt', 'r')

lines = [next(file) for x in range(3)]  # first 3 lines will be in this list

file.close()

解决方案 18:

获取前 10 行的简单方法:

with open('fileName.txt', mode = 'r') as file:
    list = [line.rstrip('
') for line in file][:10]
    print(list)

解决方案 19:

详细说明GM之前的回答:

如果您想快速读取第一行,并且稍微关心性能,则可以使用 .readlines(),它返回列表对象,然后对列表进行切片 [0:5],但在 sizehint 参数中为其提供要读取的字节数(1024)

    with open("pathofmyfileandfileandname") as myfile:
        firstNlines=myfile.readlines(1024)[0:5] 
        # (): max byte count to read from file 
        # []: put here the interval you want

仅读取文件的某些第一部分(字节数四舍五入到下一个缓冲区大小)(如果您正在浏览较大的数据文件,这会加快该过程)。

Python 文件 readlines() 方法中的语法参考

解决方案 20:

只需使用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)

解决方案 21:

#!/usr/bin/python

import subprocess

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

output, err = p.communicate()

print  output

这个方法对我有用

相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1565  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1354  
  信创国产芯片作为信息技术创新的核心领域,对于推动国家自主可控生态建设具有至关重要的意义。在全球科技竞争日益激烈的背景下,实现信息技术的自主可控,摆脱对国外技术的依赖,已成为保障国家信息安全和产业可持续发展的关键。国产芯片作为信创产业的基石,其发展水平直接影响着整个信创生态的构建与完善。通过不断提升国产芯片的技术实力、产...
国产信创系统   21  
  信创生态建设旨在实现信息技术领域的自主创新和安全可控,涵盖了从硬件到软件的全产业链。随着数字化转型的加速,信创生态建设的重要性日益凸显,它不仅关乎国家的信息安全,更是推动产业升级和经济高质量发展的关键力量。然而,在推进信创生态建设的过程中,面临着诸多复杂且严峻的挑战,需要深入剖析并寻找切实可行的解决方案。技术创新难题技...
信创操作系统   27  
  信创产业作为国家信息技术创新发展的重要领域,对于保障国家信息安全、推动产业升级具有关键意义。而国产芯片作为信创产业的核心基石,其研发进展备受关注。在信创国产芯片的研发征程中,面临着诸多复杂且艰巨的难点,这些难点犹如一道道关卡,阻碍着国产芯片的快速发展。然而,科研人员和相关企业并未退缩,积极探索并提出了一系列切实可行的解...
国产化替代产品目录   28  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用