Reading a File in Python
We have the following methods to read the content of the file in python:
- read() : It returns the entire file content
- readline() : Reads the single line at a time.
- 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 | |
---|---|
r | Read-only mode. This is the default mode. |
r+ | Read and Write |
rb | Read in binary format |
w+ | Read and Write. It will truncate the file if it already exists. |
a+ | Read and append. |
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()
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()
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()