Reading a Line From File Without Advancing [Pythonic Approach]

后端 未结 5 2095
日久生厌
日久生厌 2021-01-01 10:24

What\'s a pythonic approach for reading a line from a file but not advancing where you are in the file?

For example, if you have a file of

cat1
cat2         


        
5条回答
  •  余生分开走
    2021-01-01 10:51

    Manually doing it is not that hard:

    f = open('file.txt')
    line = f.readline()
    print line
    >>> cat1
    # the calculation is: - (length of string + 1 because of the \n)
    # the second parameter is needed to move from the actual position of the buffer
    f.seek((len(line)+1)*-1, 1)
    line = f.readline()
    print line
    >>> cat1
    

    You can wrap this in a method like this:

    def lookahead_line(file):
        line = file.readline()
        count = len(line) + 1
        file.seek(-count, 1)
        return file, line
    

    And use it like this:

    f = open('file.txt')
    f, line = lookahead_line(f)
    print line
    

    Hope this helps!

提交回复
热议问题