ADVERTISEMENT
ADVERTISEMENT

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.
Submitted by Shivang Yadav, on March 15, 2021

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.

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 »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.