File Handling. Get data from File and Print on Screen.
At First step we open file in Read Only Mode. Read lines using readline() and print on screen. Run in loop till end of file and read line by line. We format the data using ‘\t’ tab. Do some totaling on Salary and show the result on screen below the salary column. We use int() to convert string to integer for totaling and use str() to convert int to string. Finally we close the file.
#Open file in read mode with print data on Screen
r_file=open("person.txt","r")
d_data = r_file.readline()
print d_data
r_file.close()
#Open file in loop to read all data in file and print
print "\t <---name-->"
print "First\tMiddle\tLast\tAge\tSalary"
tot=0
with open("person.txt") as r_file:
while True:
d_data=r_file.readline()
if not d_data :
break
f_data=d_data.split(",")
name=f_data[0].split(" ")
tot +=int(f_data[2])
print name[0],'\t'+name[1],'\t'+name[2],'\t'+f_data[1],'\t'+f_data[2]
print "\t\t\t\t"+str(tot)
Result

At First step we open file in Read Only Mode. Read lines using readline() and print on screen. Run in loop till end of file and read line by line. We format the data using ‘\t’ tab. Do some totaling on Salary and show the result on screen below the salary column. We use int() to convert string to integer for totaling and use str() to convert int to string. Finally we close the file.
#Open file in read mode with print data on Screen
r_file=open("person.txt","r")
d_data = r_file.readline()
print d_data
r_file.close()
#Open file in loop to read all data in file and print
print "\t <---name-->"
print "First\tMiddle\tLast\tAge\tSalary"
tot=0
with open("person.txt") as r_file:
while True:
d_data=r_file.readline()
if not d_data :
break
f_data=d_data.split(",")
name=f_data[0].split(" ")
tot +=int(f_data[2])
print name[0],'\t'+name[1],'\t'+name[2],'\t'+f_data[1],'\t'+f_data[2]
print "\t\t\t\t"+str(tot)

No comments:
Post a Comment