×

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:

  1. It becomes cumbersome to handle huge amounts of data
  2. The entire data is lost when the program is terminated
  3. The data is also lost when the computer is turned off

Types of Files

Generally, there are two types of files. They are

  1. ASCII Files
  2. 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 ModifierUse
rDefault mode for opening a file just only for reading. The cursor is placed at the file starting.
rbThis 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.
wDefault mode for opening a file just only for writing. The cursor is placed at the file starting.
wbThis 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.
aDefault 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
abThis 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.


Related Topics

Django vs NodeJS

Django and NodeJS are open-source frameworks used to develop web applications. Both Django and NodeJS are cross-platform and robust technology used for developing versatile web applications and mobile applications. Django Django is...

2 minutes read.

How to Practice Python Programming

Learning python kkis a step towards coding. Python gets one closer to programming languages. It is essential to practice every programming language to become a professional in coding. It is...

4 minutes read.

How to Install Python

Python Installation Guide Step by Step Installing Python is quite simple and easy. In this tutorial, we will show stepwise procedure to install Python and set up the Python environment in different...

2 minutes read.

What is Python online compiler?

The compiler is a program that is used to scan an entire high-level program (source code) and it translates the scanned program into machine code. Compilers convert .py source code into...

5 minutes read.

Python Virtual Environment

In this tutorial, we will understand Virtual Environment in Python. We will understand the need for a virtual environment and also see how to make use of it in python....

3 minutes read.

Static Variables in Python

What is a Static Variable? The variable that remains with a constant value throughout the program or throughout the class is known as a " Static Variable ". Static variables are...

3 minutes read.

Exrex Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster...

4 minutes read.

Python Interpreter

In this tutorial, we will go through the basic knowledge about what an interpreter is and how we use it in the python programming language. It is one of the...

3 minutes read.

Anonymous/Lambda Function in Python

Lambda keyword is used to declare an Anonymous function, i.e. a function that does not have any name. It is also called Anonymous functions. In python, normal functions are defined...

3 minutes read.

How to run Python program in CMD

How to run python program in cmd Command Prompt provides us all together with a different approach for dealing with our programs. The programs can be executed by accessing the directories. In...

3 minutes read.

Python Dictionary get() method

Python Dictionary get() method The dictionary.get() method returns the value of the item with the specified key. Syntax dictionary.get(keyname, value) Parameter keyname- This parameter represents the key to be searched in the dictionary. value- The parameter...

1 minute read.

Python Setup guide and installation

Python Installation guide Step by Step Python is widely used high-level programming language. The first version of Python was launched in 1991. Since then, Python has been gaining popularity. It is considered as...

4 minutes read.

API Requests using Python

What is an API? API stands for Application Programming Interface. It is commonly known as API. It provides an environment that helps two or more computer programs to contact each other....

5 minutes read.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

3 minutes read.

Python Compiler

What is Compiler? The compiler is mainly a program used to convert the source code into the machine or binary code. The source code is generally a computer program written using...

6 minutes read.

How to convert integer to float in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

5 minutes read.

What Does the Percent Sign (%) Mean in Python?

In python, the percent sign is called modulo operator " %, " which returns the rest of partitioning the left-hand operand by the right-hand operand. Example: value1 = 8 value2 = 2 remainder =...

4 minutes read.

Python GUI Programming

GUI (Graphical User Interface) GUI is a graphics-based operating system that uses icons and menus to interact with the user. Python mostly works on CLI (Command Line Interface). Widgets Any user interface has...

4 minutes read.

Covariance in Python

Covariance is defined as the estimate of the difference of change between two variables or more variables. It defines the changes of two variables together. In Python, The covariance can...

2 minutes read.

SKLearn Linear Module

The SK learn linear module is one such module that helps to study the relationship between the independent and dependent variables.The linear module can be implemented by using the best...

3 minutes read.