Mar-17-2020, 07:10 AM
I am getting the desired output for this problem but feel that my code is very long. Please suggest if its possible to shorten the code and make it better.
METHOD USED
1.The details of the students who scored "B" grade are fetched from file.txt and then written in another text file temp.txt.
2.After that ,the data is stored in a list of lists.
3.Finally the details are stored in a dictionary and the output is displayed.
In this problem, the student details are present in a text file as shown below. It is in the format (name,grade,city)
INPUT FILE DATA:(file.txt)
Shankar,A,Chennai
Arun,B,Chennai
Karthik,A,Chennai
Raj,B,Chennai
Ram,A,Chennai
Now we need to fetch and print the details of the students who scored "B" grade in the below format.
OUTPUT:
Student 1
Student name : Arun
Grade : B
Location : Chennai
Student 2
Student name : Raj
Grade : B
Location : Chennai
METHOD USED
1.The details of the students who scored "B" grade are fetched from file.txt and then written in another text file temp.txt.
2.After that ,the data is stored in a list of lists.
3.Finally the details are stored in a dictionary and the output is displayed.
In this problem, the student details are present in a text file as shown below. It is in the format (name,grade,city)
INPUT FILE DATA:(file.txt)
Shankar,A,Chennai
Arun,B,Chennai
Karthik,A,Chennai
Raj,B,Chennai
Ram,A,Chennai
Now we need to fetch and print the details of the students who scored "B" grade in the below format.
OUTPUT:
Student 1
Student name : Arun
Grade : B
Location : Chennai
Student 2
Student name : Raj
Grade : B
Location : Chennai
from collections import OrderedDict grade=input("Enter the grade to search\n") lines=0 """Write data with the specific grade to another text file""" with open("file.txt","r") as f1: with open("temp.txt","w") as f2: for i in f1: new=i.split(",") for k in range(0,len(new)): if str(new[k])==grade: f2.write(i) f1.close() cnt=0 new=[] #Will store data as list of lists """The data is stored in a list of lists""" with open("temp.txt","r") as f2: for i in f2: cnt+=1 #Number of lines in the temp.txt file i=i.split(",") new.append(i) k=0 while(k<cnt): print "Student 1" dd1=OrderedDict() dd1["Student name:"]= new[0][0] #Access elements of a list of lists dd1["Grade:"]=new[0][1] dd1["Location:"]=new[0][2] for x,y in dd1.items(): print (x,y) k+=1 if k==cnt: break print "Student 2" dd2=OrderedDict() dd2["Student name:"]= new[1][0] #Access elements of a list of lists dd2["Grade:"]=new[1][1] dd2["Location:"]=new[1][2] for x,y in dd2.items(): print (x,y) k+=1 if k==cnt: break print "Student 3" dd3=OrderedDict() dd3["Student name:"]= new[2][0] #Access elements of a list of lists dd3["Grade:"]=new[2][1] dd3["Location:"]=new[2][2] for x,y in dd3.items(): print (x,y) k+=1 if k==cnt: break