Understand Python File readline(): A Simple Guide for Beginners – Python Tutorial

By | September 21, 2019

Python file readline() function can read a line of file, in this tutorial, we will introduce how to use function and some tips on using it.

Syntax

Python file readline() function is defined as:

fileObject.readline( size );

Parameter

size: the count of bytes from the line you want to read once.

If you do not set a size, fileObject.readline() will only read a whole line once.

Create a txt file

We create a filedemo.txt firstly.

line 1
line 2
line 3
line 4
line 5

Read a line without setting line size

line = ''
with open('filedemo.txt', 'r') as fin:
    line = fin.readline()
    
print(type(line))
print(line)

The line content is:

<class 'str'>
line 1

From the line content we will find, if you do not set a line size, you will read a whole line content.

Read line with setting line size

line = ''
with open('filedemo.txt', 'r') as fin:
    size = 3
    line = fin.readline(size)
    
print(type(line))
print(line)

The line content is:

<class 'str'>
lin

From the line content we will find: if you have set the size = 3, readline(size) will only read 3 bytes from the beginning of a line.

Read a line with negative size

line = ''
with open('filedemo.txt', 'r') as fin:
    size = -1
    line = fin.readline(size)
    
print(type(line))
print(line)

The line content is:

<class 'str'>
line 1

From the result, we will find if line size is a negative (-1) number, this function will return the whole line.

How to read all lines of a file

fileObject.readline() only can read one line of a file, how to read all lines?

Here is an example:

with open('filedemo.txt', 'r') as fin:
    for line in fin:
        print(type(line))
        print(line)

The file content is:

<class 'str'>
line 1

<class 'str'>
line 2

<class 'str'>
line 3

<class 'str'>
line 4

<class 'str'>
line 5

Here are some tips you should notice:

1.If you read a file with a binary mode, fileObject.readline() function will return a byte like object, not a string object.

line = ''
with open('filedemo.txt', 'rb') as fin:
    line = fin.readline()
    
print(type(line))
print(line)

The first line is:

<class 'bytes'>
b'line 1\r\n'

2.When this function return the whole line, the new line symbol (\r or \n) is also be returned. You can find the truth from the above example.

Leave a Reply