Read a File in Python


Reading a File in Python

We have the following methods to read the content of the file in python:

  1. read() : It returns the entire file content
  2. readline() : Reads the single line at a time.
  3. readlines() : It returns the list of all the lines of the file.

Access Modes

The following access modes are associated with reading the content of a file in python:

Mode
rRead-only mode. This is the default mode.
r+Read and Write
rbRead in binary format
w+Read and Write. It will truncate the file if it already exists.
a+Read and append.
File modes

read()

The read() method is used to read the entire file. It has the optional argument to specify the n bytes.

In [1]:
f = open("readme.txt",'r')
print(f.read())
f.close()
Welcome to Logical Python.
Best place to learn Python.
Thanks for visiting.

readline()

It reads the file line by line. Means, it first reads the first line and returns it, then the second and so on.

In [1]:
f = open("readme.txt",'r')
print(f.readline())
print(f.readline())
f.close()
Welcome to Logical Python.

Best place to learn Python.

readlines()

It reads all the lines of the file and returns a list. Each line is an individual element of the list.

In [1]:
f = open("readme.txt",'r')
print(f.readlines())
f.close()
['Welcome to Logical Python.\n', 'Best place to learn Python.\n', 'Thanks for visiting.']