Skip to content Skip to sidebar Skip to footer

Python Readline - Reads Only First Line

#1 input_file = 'my-textfile.txt' current_file = open(input_file) print current_file.readline() print current_file.readline() #2 input_file = 'my-textfile.txt' print open(input_fi

Solution 1:

When you call open you are opening the file anew and starting from the first line. Every time you call readline on an already open file it moves its internal "pointer" to the start of the next line. However, if you re-open the file the "pointer" is also re-initialized - and when you call readline it reads the first line again.

Imagine that open returned a file object that looked like this:

classFile(object):
    """Instances of this class are returned by `open` (pretend)"""def__init__(self, filesystem_handle):
        """Called when the file object is initialized by `open`"""print"Starting up a new file instance for {file} pointing at position 0.".format(...)

        self.position = 0
        self.handle = filesystem_handle


    defreadline(self):
        """Read a line. Terribly naive. Do not use at home"

        i = self.position
        c = None
        line = ""
        while c != "\n":
            c = self.handle.read_a_byte()
            line += c

        print "Read line from {p} to {end} ({i} + {p})".format(...)

        self.position += i
        return line

When you ran your first example you would get something like the following output:

Starting up a new file instance for /my-textfile.txt pointing at position0.
Read line from0to80 (80 + 0)
Read line from80to160 (80 + 80)

While the output of your second example would look something like this:

Starting up a new file instance for /my-textfile.txt pointing at position0.
Read line from0to80 (80 + 0)
Starting up a new file instance for /my-textfile.txt pointing at position0.
Read line from0to80 (80 + 0)

Solution 2:

The second snippet opens the file twice, each time reading one line. Since the file is opened afresh, each time it is the very first line that's getting read.

Post a Comment for "Python Readline - Reads Only First Line"