代码之家  ›  专栏  ›  技术社区  ›  Russell

在python中读取文件的前n行

  •  113
  • Russell  · 技术社区  · 15 年前

    我们有一个大的原始数据文件,我们想修剪到指定的大小。 我在.NET C方面很有经验,但是我希望在Python中这样做,以简化事情并使之失去兴趣。

    如何获取Python中文本文件的前n行? 正在使用的操作系统对实现有什么影响吗?

    13 回复  |  直到 6 年前
        1
  •  190
  •   anilbey    6 年前

    Python 2

    with open("datafile") as myfile:
        head = [next(myfile) for x in xrange(N)]
    print head
    

    Python 3

    with open("datafile") as myfile:
        head = [next(myfile) for x in range(N)]
    print(head)
    

    这是另一种方法(python 2&3)

    from itertools import islice
    with open("datafile") as myfile:
        head = list(islice(myfile, N))
    print head
    
        2
  •  15
  •   Community CDub    6 年前
    N = 10
    file = open("file.txt", "a")#the a opens it in append mode
    for i in range(N):
        line = file.next().strip()
        print line
    file.close()
    
        3
  •  11
  •   G M    8 年前

    如果你想快速阅读第一行,而不关心性能,你可以使用 .readlines() 它返回列表对象,然后对列表进行切片。

    例如,前5行:

    with open("pathofmyfileandfileandname") as myfile:
        firstNlines=myfile.readlines()[0:5] #put here the interval you want
    

    注: 整个文件都被读取了 从性能角度看不是最好的 但它 易于使用、书写速度快且易于记忆,因此如果您只想执行 一次性计算非常方便

    print firstNlines
    
        4
  •  7
  •   RRuiz    8 年前

    我要做的是使用 pandas . 我认为表演不是最好的,但例如 N=1000 :

    import pandas as pd
    yourfile = pd.read('path/to/your/file.csv',nrows=1000)
    
        5
  •  5
  •   u0b34a0f6ae    15 年前

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

    我想最简单的方法是:

    lines =[]
    with open(file_name) as f:
        lines.extend(f.readline() for i in xrange(N))
    
        6
  •  4
  •   fdb    14 年前

    基于gnibler的顶部投票答案(09年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('\n')
            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)
    
        7
  •  4
  •   FatihAkici    7 年前

    最直观的两种方法是:

    1. 逐行迭代文件,以及 break 之后 N 线。

    2. 使用 next() 方法 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 将整个文件保存到内存中,您有很多选择。

        8
  •  3
  •   Maxim Plaksin    13 年前

    我自己最方便的方式:

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

    解决方案基于 List Comprehension 函数open()支持迭代接口。enumerate()包含open()和返回元组(index,item),然后检查我们是否在可接受的范围内(如果i<line_count),然后简单地打印结果。

    享受蟒蛇吧。;)

        9
  •  2
  •   John Machin Santi    15 年前

    如果您想要一些明显的东西(不需要在手册中查找深奥的东西),不需要导入和尝试/排除,并且可以在相当多的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)
    
        10
  •  2
  •   Steve Bading    12 年前

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

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

    (您不必担心您的文件少于n行,因为不会引发StopIteration异常。)

        11
  •  2
  •   Alejandro D. Somoza    10 年前

    如果您有一个非常大的文件,并且假设您希望输出是一个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
  •  2
  •   Surya    8 年前

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

    N=5
    with open("data_file", "r") as file:
        for i in range(N):
           print file.next()
    
        13
  •  1
  •   Eric Aya    7 年前
    #!/usr/bin/python
    
    import subprocess
    
    p = subprocess.Popen(["tail", "-n 3", "passlist"], stdout=subprocess.PIPE)
    
    output, err = p.communicate()
    
    print  output
    

    这种方法对我有用