Reputation: 183
I have the following Class created:
class Student:
def __init__(self, name, id, email):
self.__name = name
self.__id = id
self.__email_id = email
self.__marks = []
#accessors
def get_name(self):
return self.__name
def get_email(self):
return self.__email_id
def get_id(self):
return self.__id
def get_marks(self):
return self.__marks
#mututators
def set_name(self, name):
self.__name = name
def set_id(self, id):
self.__id = id
def set_email(self, email):
self.__email_id = email
def set__marks(self, marks):
self.__marks = marks
#formatted string representation of the student
def __str__(self):
return "%s: %s, %s, marks: %s" % (self.__id, self.__name, self.__email_id, self.__marks)
#appends the marks to the end of the marks list
def append_marks(self, marks):
self.__marks.append(marks)
When I call this class in the following function:
def read_classlist():
#This function reads the classlist from file.
global studentslist
studentslist = []
try:
file=input("Enter name of the classlist file: ")
with open(file) as f:
for line in f:
data=line.split(",")
s=Student(data[0],data[1],data[2])
studentslist.append(s)
print("Completed reading of file %s" % file)
for student in studentslist:
print(student)
display_separator()
menu()
return
except IOError:
print("File %s could not be opened" % file)
display_separator()
menu()
return
It's not printing the text properly. For some reason, it messes up the formatting for everything but the last student.
Example:
Enter name of the classlist file: classlist.txt
Completed reading of file classlist.txt
N00000001: John, [email protected]
, marks: []
N00000002: Kelly, [email protected]
, marks: []
N00000003: Nicky, [email protected]
, marks: []
N00000004: Sam, [email protected]
, marks: []
N00000005: Adam, [email protected], marks: []
I can't figure out why it's creating a new line after the email. It's doing that for every data file, but the last student being displayed will always be correct.
I don't quite understand it.
Any help would be great!
Upvotes: 1
Views: 47
Reputation: 9257
I think you should change this line
data=line.split(",")
to
data=line.rstrip().split(",")
This'll delete the return to a new line character \n
from your data and you'll have your desired output.
Upvotes: 1