Read contents of a file using readline() method and manipulating it in Python

Python | Read contents of the file: In this tutorial, we will learn how to read the contents of the file using the readline() method and manipulate the data in Python. By Shivang Yadav Last updated : July 05, 2023

Program Statement

Python program to read contents of a file and manipulate data while printing.

Program Description

We will read the contents of the file using readline() method and then append the data to the end after manipulating it. 

We will use the concepts of file handling in python to append the contents to the file using readline() and append() method.

  • The readline() method is used to read content from data line by line.

Reading contents of a file using readline() method and manipulating it

The steps to read the contents of the file using the readline() method and manipulating it in Python are as follows,

  • Step 1: Open the file in append mode using 'r'.
  • Step 2: Get the input data from the user and store it.
  • Step 3: Manipulate the data using some operation.
  • Step 4: Print the resultant data.

Python program to read contents of a file using readline() method and manipulating it

F=open("data.dat","r")
while(True):
    data=F.readline()
    if(data==""):break
    DL=data.split(",")
    DL[2]=DL[2].rstrip("\n")
    DL.append(int(DL[2])*20/100)
    print(DL)
F.close()

Output

['10032', 'John Doe', '45000', 9000.0]
['10323', 'Ram', '50000', 10000.0]

In the above code, we have read data from a file named 'data.dat'. And then perform the manipulation operation on data and print it.

Python file handling programs »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.