Q:

Python program to read data from file and extract record data from it

belongs to collection: Python file handling programs

0

File Handling in Python is reading and writing data from files. Programs can interact with files and data using the concept of file handling.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python program to delete a file... >>
<< Python program to check a file\'s status in f...