Python file readlines() method

Python file readlines() method

The readlines() method reads until EOF using readline() and returns a list containing the lines. If the optional sizehint parameter is present, rather than reading until EOF, a whole line of approximately sizehint bytes will be read (possibly rounded up to the internal buffer size).

An empty string is returned only if EOF is encountered immediately.

Syntax

The following is the syntax of the readlines() method −

fileObject.readlines(sizehint)

Parameters

  • sizehint − This is the number of bytes to read from the file.

Return Value

This method returns a list containing the lines.

The following example shows the usage of the readlines() method.

Suppose the ‘foo.txt’ file contains the following text −

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

Example

# Open a file
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.readlines()
print ("Read Line: %s" % (line))
line = fo.readlines(2)
print ("Read Line: %s" % (line))

# Close the opened file
fo.close()

When we run the above program, it produces the following output.

Name of the file: foo.txt
Read Line: ['This is 1st linen', 'This is 2nd linen',
            'This is 3rd linen', 'This is 4th linen',
            'This is 5th linen']
Read Line:

Leave a Reply

Your email address will not be published. Required fields are marked *