×

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

Python File Handling

What is the file? The file is a collection of data in a single unit. It is used to store information in the non-volatile memory such as hard-disk. Computer programs generally run on the RAM...

7 minutes read.

Python Control Flow Statements

This article aims to introduce you to what control flow statements are in general and Control Flow Statements in Python programming Language, the Importance of control flow statements and look...

3 minutes read.

Cross Validation in Sklearn

Data scientists can benefit from cross-validation in machine learning in two key ways: it can assist in minimising the amount of data needed and ensure the artificial intelligence model is...

14 minutes read.

Python Dictionary setdefault() method

Python Dictionary setdefault() method The dictionary.setdefault () method in Python returns the value of the item with the specified key. Syntax dictionary.setdefault(keyname, value) Parameter keyname- This parameter represents the keyname of the item you want...

1 minute read.

Weight Conversion GUI using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 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.

Python getattr() function

Python getattr() function The getattr() function in Python returns the value of the named attribute for the given object. Syntax getattr(object, name[, default]) Parameter object: It is a required parameter which represents an object. name: This parameter represents the...

1 minute read.

What is online python free IDE

An IDE is an acronym that stands for “Integrated development environment.” It is a software environment that has a software development package that consists of the code editor and builds...

4 minutes read.

Scraping data in python

Data scraping is a technique in which one program extracts a set of data from the output of another program. Web scraping is the most common application of this technique....

6 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.

How to Create an Array in Python?

How to Create an Array in Python In the previous article, we have discussed how to declare an array in Python. So, let's have a quick revision of that, and then we...

5 minutes read.

Compound Interest GUI Calculator using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

6 minutes read.

Python len() function

Python len() function The len() function in Python  returns the number of items in an object. Syntax len(s) Parameter s: This parameter represents a sequence (such as a string, bytes, tuple, list, or range) or...

1 minute read.

Python Matrix Multiplication

One of the most fundamental mathematical structures, matrices are used often in many disciplines, including mathematics, physics, engineering, computer science, etc. For example, matrices and associated operations (multiplication and addition) are...

8 minutes read.

Python Tutorial

Python tutorial is a widely used programming language which helps beginners and professionals to understand the basics of Python programming easily. Python is a high-level, easy, interpreted, general-purpose, and dynamic programming...

19 minutes read.

PyShark in 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 way....

4 minutes read.

Latest Project Ideas using Python 2024

Python is one of the well-known languages for programming in the contemporary domain of computer science. The demand to adopt Python for IT purposes is steadily increasing because of its...

7 minutes read.

Anytree Python

Python's anytree module is frequently used within data science-related software. Anytree has a Tolerant License, a Construct File that is public, no errors, no risks, and excellent support. One may...

3 minutes read.

Python tokens and character set

In this tutorial, we will understand what are character sets used in python and what is meant by python tokens and we will further discuss the type of tokens being...

4 minutes read.

Check if a String is Empty in Python

The string is one of the data types of Python. This data type stores all kinds of data but all the characters must be enclosed using double quotes (""). In...

5 minutes read.