Easy Tutorial
❮ Python Counting Sort Ref Math Factorial ❯

Python3 File readlines() Method

Python3 File Methods


Overview

The readlines() method is used to read all lines until the end-of-file (EOF) and returns a list, which can be processed by Python's for... in ... structure. If it encounters the end-of-file (EOF), it returns an empty string.

Syntax

The syntax for the readlines() method is as follows:

fileObject.readlines();

Parameters

-

None.

Return Value

Returns a list containing all the lines.

Example

The following example demonstrates the use of the readline() method:

The content of the file tutorialpro.txt is as follows:

1:www.tutorialpro.org
2:www.tutorialpro.org
3:www.tutorialpro.org
4:www.tutorialpro.org
5:www.tutorialpro.org

Loop through the file's content:

Example (Python 3.0+)

#!/usr/bin/python3

# Open file
fo = open("tutorialpro.txt", "r")
print("File name: ", fo.name)

for line in fo.readlines():                          # Read each line  
    line = line.strip()                             # Remove leading and trailing whitespace  
    print("Data read: %s" % (line))

# Close file
fo.close()

The above example outputs the following results:

File name:  tutorialpro.txt
Data read: 1:www.tutorialpro.org
Data read: 2:www.tutorialpro.org
Data read: 3:www.tutorialpro.org
Data read: 4:www.tutorialpro.org
Data read: 5:www.tutorialpro.org

Python3 File Methods

❮ Python Counting Sort Ref Math Factorial ❯