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

检查文本文件是否有另一行Python

  •  1
  • yourknightmares  · 技术社区  · 7 年前

    我正在编写一个脚本,将文本文件解析为电子表格,这样我就需要通读它们。问题是找出何时停止。Java在读取调用时附加了一个方法 hasNext() hasNextLine() 我想知道Python中是否有类似的东西?不知为什么我哪儿也找不到这个。

    open(f) as file:
        file.readline()
        nextLine = true
        while nextLine:
            file.readline()
            Do stuff
            if not file.hasNextLine():
                nextLine = false
    
    5 回复  |  直到 7 年前
        1
  •  3
  •   rahlf23    7 年前

    我用来阅读文本文件的典型节奏是:

    with open('myfile.txt', 'r') as myfile:
    
        lines = myfile.readlines()
    
    for line in lines:
    
        if 'this' in line: #Your criteria here to skip lines
            continue
    
        #Do something here
    

    使用 with 只会保持文件打开,直到您执行了它的块中的所有代码,然后文件将被关闭。我也认为强调 readlines() 方法,它读取文件中的所有行并将它们存储在列表中。在处理新线方面( \n )人物,我会给你指出@Joe Iddon的答案。

        2
  •  4
  •   Joe Iddon    7 年前

    for line in file:
        #do stuff..
    

    注意,这包括新行char( \n line 弦。这可以通过以下任一方式删除:

    for line in file:
        line = line[:-1]
        #do stuff...
    

    或:

    for line in (l[:-1] for l in file):
        #do stuff...
    

    file.tell 没有任何读数)。

    这可以通过打电话来完成 file.readline 并检查字符串是否为空或 timgeb's method next 抓住 StopIteration 例外。

    因此,要准确回答您的问题,您可以检查文件是否有另一行:

    next_line = file.readline():
    if next_line:
        #has next line, do whatever...
    

    def has_another_line(file):
        cur_pos = file.tell()
        does_it = bool(file.readline())
        file.seek(cur_pos)
        return does_it
    

    它重置文件指针,将文件对象重置回其原始状态。

    例如

    $ printf "hello\nthere\nwhat\nis\nup\n" > f.txt
    $ python -q
    >>> f = open('f.txt')
    >>> def has_another_line(file):
    ...     cur_pos = file.tell()
    ...     does_it = bool(file.readline())
    ...     file.seek(cur_pos)
    ...     return does_it
    ... 
    >>> has_another_line(f)
    True
    >>> f.readline()
    'hello\n'
    
        3
  •  1
  •   timgeb    7 年前

    文件是行上的迭代器。如果你只想检查一个文件是否还有一行,你可以 line = next(file) StopIeration 在没有其他行的情况下引发。或者你可以使用 line = next(file, default) 带非字符串 default 价值(例如。 None )然后对照一下。

    for 正如其他答案所解释的,循环文件结束。所以要确保你真的需要这种细粒度的控制 next

        4
  •  1
  •   Matthias Fripp    7 年前

    Python没有文件结束(EOF)指示器,但是您可以通过这种方式获得相同的效果:

    with open(f) as file:
        file.seek(0, 2)      # go to end of file
        eof = file.tell()    # get end-of-file position
        file.seek(0, 0)      # go back to start of file
        file.readline()
        nextLine = True      # maybe nextLine = (file.tell() != eof)
        while nextLine:
            file.readline()
            # Do stuff
            if file.tell() == eof:
                nextLine = False
    

    但正如其他人指出的那样,将文件视为iterable可能会做得更好,例如:

    with open(f) as file:
        next_line = next(file)
        # next loop will terminate when next_line is '', 
        # i.e., after failing to read another line at end of file
        while next_line:
            # Do stuff
            next_line = next(file)
    
        5
  •  1
  •   Swift    7 年前
    with open(filepath, 'rt+') as f:
        for line in f.readlines():
            #code to process each line
    

    以这种方式打开它也会在它完成时关闭它,这对总体内存使用情况要好得多,这可能与文件大小无关。

    第一行相当于:

    f = open(....)

    f.readlines()

    循环将从第一行开始,然后在最后一行结束,例如,不应该抛出有关EOF的任何错误。

    [编辑]

    注意open方法中的“rt+”。据我所知,这将以读文本模式打开文件。一、 不需要解码。