Home »
Python »
Python programs
Python program to read data from file and extract record data from it
Here, we will see a program in which we will read lines from a file, these lines represent the record of a company's employees. We will extract each data from the record and print it.
By Shivang Yadav Last updated : July 05, 2023
File Handling in Python is reading and writing data from files. Programs can interact with files and data using the concept of file handling.
Here, we will extract data line by line and then split the data to print it on the screen.
Python program to read data and print extracted records
# program to read data and extract records
# from it in python
# Opening file in read format
File = open('file.dat',"r")
if(File == None):
print("File Not Found..")
else:
while(True):
# extracting data from records
record = File.readline()
if (record == ''): break
data = record.split(',')
data[3] = data[3].strip('\n')
# printing each record's data in organised form
print('Code:',data[0])
print('Name:', data[1])
print('Salary:', data[2])
print('City:', data[3])
File.close()
File : File.dat
001,John,35000,London
002,Jane,50000,NewYork
003,Ram,125000,Delhi
Output
Code: 001
Name: John
Salary: 35000
City: London
Code: 002
Name: Jane
Salary: 50000
City: NewYork
Code: 003
Name: Ram
Salary: 125000
City: Delhi
Explanation
In the above code, we have opened a file and then extracted data from it line by line using readline() and then from each line, we have extracted data which are separated by comma "," in the file. And then printed the separated record.
Python file handling programs »