Reading a File Line by Line in Python
Introduction
In this tutorial, we will learn about reading files in python line by line. Before reading the files, let us know a little information about the files first.
Files
A file is a collection of data that is stored in hard disk also known as secondary storage devices. Till now we have processed data using input () method. But these methods cannot take huge amounts of data for processing. So, for better solution we are using files concept.
When the program is running, its content is stored in Random Access Memory (RAM). A file is used basically because real life applications involve large amounts of data in such situations the console pose a few problems like:
- It becomes cumbersome to handle huge amounts of data
- The entire data is lost when the program is terminated
- The data is also lost when the computer is turned off
Types of Files
Generally, there are two types of files. They are
- ASCII Files
- Binary Files
ASCII Files
Here, each line contains a maximum character of 255 (two hundred and fifty five)
Binary Files
A binary file is a file that contains any type of data. This includes types of files like word, pdf, doc, images, sheets etc. A binary file is a group of bits which are together. It is also known as stream of characters.
Files in built Functions
- open()
For reading or writing a file, the first task we need to perform is file opening. Without opening a file, we cannot perform the task of using a file.
The in-built method open () is used to open the file. After opening the files, we need to set the mode of the files.
Syntax:
file name = open ( file_name, access mode)
Access Modifiers in Files
Access Modifier | Use |
r | Default mode for opening a file just only for reading. The cursor is placed at the file starting. |
rb | This mode opens a file in reading only in binary format. The cursor is placed at the file starting. |
r+ | This mode opens a file in both reading and writing mode. The cursor is placed at the file starting. |
w | Default mode for opening a file just only for writing. The cursor is placed at the file starting. |
wb | This mode opens a file in writing only in binary format. The cursor is placed at the file starting. |
w+ | This mode opens a file in both reading and writing mode. The cursor is placed at the file starting. |
a | Default mode for opening a file just only for appending. The cursor is placed at the file ending, only if file exists. If no file a new file is created for writing |
ab | This mode opens a file in append mode only in binary format. The cursor is placed at the file ending, only if file exists. If no file a new file is created for writing. |
a+ | This mode opens a file in both reading and appending mode. The cursor is placed at the file ending, only if file exists. If no file a new file is created for reading and writing. |
Example:
File Name: tutorial.txt
Vikram
Kamal Haasan
Anirudh
Fahadh Faasil
Vijay Sethupathi
File Name: files.py
# opening a file for reading the data present in the file
f=open('tutorial.txt','r')
# Storing the data of txt file in a variable
# reading the file and stored it’s in Lines
print(“ The content present in tutorial.txt is: ”)
Lines=f.read()
# printing the data stored in Lines
print (Lines)
# Every file opened must be closed
# close() helps in closing the file.
f.close()
Output:
The content present in tutorial.txt is:
Vikram
Kamal Haasan
Anirudh
Fahadh Faasil
Vijay Sethupathi
This is how open method is used.
- close()
Every file opened must be closed, according to the rules of the files concept in python.
So, we can finally conclude that number of open methods used is equal to number of close methods used.
Syntax:
file object. close()
- read()
This is the method that is available when the mode of accessing is in r, r+, w+, etc. This helps us view the items or content present in the file created.
Syntax:
File object. Read()
Example:
# Opening a file in read only mode
# The file object name is f
f = open(‘JAVATPOINT.txt’,’r’)
# Printing the contents present in the file using f.read()
print(f.read())
# every file opened must be closed
f.close()
Output:
Vikram
Kamal Haasan
Anirudh
Fahadh Faasil
Vijay Sethupathi
This is how we read and open a file using python files concept.
Now let us learn about how read a given file line by line using python file in built methods.
Methods used to Read Files Line by Line
Following are the methods used for reading the file line by line:
- readlines() Method
This is the in-built method used when the file is in read only mode (r), read write mode (r+).
Let us see how this method works.
Syntax:
File_object_name. readlines()
Example:
Let us understand this method with the help of an example
# file opening in read only mode
file1 = open ('JAVATPOINT.txt', 'r')
# Using readlines() method
F= file1.readlines ()
print (FileLines)
# Creating a count variable
count = 0
# Using for loop for printing them
for line in F:
count += 1
print (" FileLine %d : %s" %(count, line))
Output:
['Vikram\n', 'Kamal Haasan\n', 'Anirudh\n', 'Fahadh Faasil\n', 'Vijay Sethupathi']
FileLine1: Vikram
FileLine2: Kamal Haasan
FileLine3: Anirudh
FileLine4: Fahadh Faasil
FileLine5: Vijay Sethupathi
Explanation:
The readlines method actually takes all the values at a time into a variable. The content is taken into a delimiter called square brackets.
Example:
['Vikram\n', 'Kamal Haasan\n', 'Anirudh\n', 'Fahadh Faasil\n', 'Vijay Sethupathi']
This kind of data is not reading friendly. So, we use loops to print them line by line. The ‘\n’ after each and every word makes the output to skip the line.
Loop helps us in printing the output line by line.
- readline() Method
This is also an in-built method used to print a line when the file is opened in read only mode (r) or read write mode (r+) mode.
Syntax:
File_object name .readline()
Example:
# file opened in read only mode
f = open(‘JAVATPOINT.txt', 'r')
# Using readline() method
F = f.readline()
print(FileLines)
count = 0
# Strips the newline character
for line in F:
count += 1
showing the file contents with
print("FileLine%d: %s"%(count, line.strip()))
f.close()
Output:
Vikram
FileLine1: V
FileLine2: i
FileLine3: k
FileLine4: r
FileLine5: a
FileLine6: m
FileLine7:
Explanation:
This method readline() as the name suggests reads only a single line at a time and is stored in a single variable.
So, here when the FileLines is put under a loop, then the string Vikram is split up into different sub strings and printed.
So, to avoid this problem we put the readline() the in the loop.
Now, let us resolve this problem by putting the method inside the loop.
Resolving Code:
# opening a file in read only mode.
f=open ('JAVATPOINT.txt','r')
count=0
while (1):
# using the in built function readline()
F= file1.readline ()
count =count+1
# Termination Condition
if not F:
break
# showing the file line by line
print("Line %d : %s"%(count,FileLines.strip()))
f.close()
Output:
Line 1: Vikram
Line 2: Kamal Haasan
Line 3: Anirudh
Line 4: Fahadh Faasil
Line 5: Vijay Sethupathi
.strip method prevents the line from skipping due to the presence of ‘\n’
- read() Method
The contents of a file can be printed line by line using a simple in built method known as read() method.
Example:
# opening the file in read only mode
f=open ('JAVATPOINT.txt','r')
# reading the file
print(f.read())
# closing the file
f.close()
Output:
Vikram
Kamal Haasan
Anirudh
Fahadh Faasil
Vijay Sethupathi
- Using For loop
By using for loop on the file object name gives us the files in line by line way.
Example:
# reading the file in read only mode
f=open('JAVATPOINT.txt','r')
# using for loop for printing the values
for l in f:
print(l)
# closing the file
f.close()
Output:
Vikram
Kamal Haasan
Anirudh
Fahadh Faasil
Vijay Sethupathi
This is how we can print the values line by line using python in files.