Reading a Line From File Without Advancing [Pythonic Approach]

后端 未结 5 2063
日久生厌
日久生厌 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条回答
  •  梦毁少年i
    2021-01-01 11:09

    As far as I know, there's no builtin functionality for this, but such a function is easy to write, since most Python file objects support seek and tell methods for jumping around within a file. So, the process is very simple:

    • Find the current position within the file using tell.
    • Perform a read (or write) operation of some kind.
    • seek back to the previous file pointer.

    This allows you to do nice things like read a chunk of data from the file, analyze it, and then potentially overwrite it with different data. A simple wrapper for the functionality might look like:

    def peek_line(f):
        pos = f.tell()
        line = f.readline()
        f.seek(pos)
        return line
    
    print peek_line(f) # cat1
    print peek_line(f) # cat1
    

    You could implement the same thing for other read methods just as easily. For instance, implementing the same thing for file.read:

    def peek(f, length=1):
        pos = f.tell()
        data = f.read(length) # Might try/except this line, and finally: f.seek(pos)
        f.seek(pos)
        return data
    
    print peek(f, 4) # cat1
    print peek(f, 4) # cat1
    

提交回复
热议问题