Formatting issue when printing - python-3.x

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, john#amail.com
, marks: []
N00000002: Kelly, kelly#bmail.com
, marks: []
N00000003: Nicky, nicky#cmail.com
, marks: []
N00000004: Sam, sam#dmail.com
, marks: []
N00000005: Adam, adam#amail.com, 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!

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.

Related

NameErrors within a class

When I try to run this code I get a name error. NameError: name 'information' is not defined. I have no idea why this code isn't working on several examples ive seen code like this runs without issue. I apologize if the solution is very simple I'm new to python.
class information:
def __init__(self, name, age, phone, address='unknown'):
self.__name = name
self.__age = age
self.__address = address
self.__phone = phone
def get_Name(self):
return self.__name
def set_Name(self,name):
self.__name = name
def get_age(self):
return self.__age
def set_age(self):
self.__age = age
def get_address(self):
return self.__address
def set_address(self):
self.__address = address
def get_phone(self):
return self.__phone
def set_phone(self):
self.__phone = phone
def __str__(self):
return'name: {} – age: {} – address: {}'.format(self.__name, self.__age, self.__phone)
if __name__ == '__main__':
h1 = information('John', 27, '5193467891', 'Canada')
print(h1)

Python: creating a dictionary: {int, class object} in a loop

I'd like to create a dictonary: {int, Class} in a loop, however the class object is being overriden.
I am pretty sure that this is a basic problem, but I am stuck
class Simple:
simpleDic = {
'name': {""},
'age': {1}}
def __init__(self, name, age):
self.simpleDic['name'] = name
self.simpleDic['age'] = age
def __str__(self):
return "{} {}\n".format(self.simpleDic['name'], self.simpleDic['age'])
def foo():
myDict = {}
for x in range(3):
myDict[x] = Simple('Name' + str(x), x)
print(('{}: {}\n'.format("Creating", myDict[x])))
for key in myDict:
print(('{}: {}\n'.format("Printing" + str(key), myDict[key])))
#### Main program here ####
foo()
The output is as follows:
You're problem is on the last print
You're printing myDict[x] when you should print myDict[key]
x contains the last value from the first iteration, so you're practically printing the same key all over
Following your question in this comments:
class Simple:
def __init__(self, name, age):
self.simpleDic = {"name": name, "age": age}
def __str__(self):
return "{} {}\n".format(self.simpleDic['name'], self.simpleDic['age'])
def __repr__(self):
return "{} {}\n".format(self.simpleDic['name'], self.simpleDic['age'])
def foo():
myDict = {}
for x in range(3):
myDict[x] = Simple('Name' + str(x), x)
print(('{}: {}\n'.format("Creating", myDict[x])))
print(myDict)

Duplicate a string in Tkinter when redirecting output to a text field

I redirect all my output to the program text field in Tkinter and I wanted to add a date and time to the message:
class StdRedirector(object):
def __init__(self, text_field):
self.text_field = text_field
def write(self, string):
msg_time = datetime.now().strftime('%m-%d %H:%M:%S')
self.text_field.configure(state='normal')
self.text_field.insert('end', f'{msg_time} >> {string}')
self.text_field.see('end')
self.text_field.configure(state='disabled')
class App:
def __init__(self):
self.builder = pygubu.Builder()
self.__init_ui()
self.__init_callbacks()
self.mainwindow.mainloop()
def __init_ui(self):
self.builder.add_from_file(path.join(base_dir, 'assets', 'app.ui'))
self.mainwindow = self.builder.get_object('mainwindow')
self.output_text_field = self.builder.get_object('output_text_field')
sys.stdout = StdRedirector(self.output_text_field)
sys.stderr = StdRedirector(self.output_text_field)
def __init_callbacks(self):
callbacks = {
'update_balance_function': self.__update_balance
}
self.builder.connect_callbacks(callbacks)
def __update_balance(self):
print(True)
But the date line I added is duplicated:
As I understand it, the line is separated by the line separator \n and each substring is sent separately, including line break. Can I fix it somehow?
You can simply check whether the string argument in write() contains any meaningful content, e.g. using ìf string.strip():
class StdRedirector(object):
def __init__(self, text_field):
self.text_field = text_field
def write(self, string):
self.text_field.configure(state='normal')
if string.strip(): # add date before message
msg_time = datetime.now().strftime('%m-%d %H:%M:%S')
self.text_field.insert('end', f'{msg_time} >> {string}')
else: # simply insert string
self.text_field.insert('end', string)
self.text_field.see('end')
self.text_field.configure(state='disabled')

Implementation of MVC Design Pattern in Python3

I am trying to implement MVC using Python3.8. I have used this https://www.tutorialspoint.com/python_design_patterns/python_design_patterns_model_view_controller.htm Python2's example for practice.
But, I am receiving the following error:
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
My code is as following:
model.py
import json
class Person:
def __init__(self, first = None, last = None):
self.first = first
self.last = last
def name(self):
return ('%s %s' %(self.first, self.last))
#classmethod
def getAll(self):
database = open('data.txt', 'r')
result = []
jsonList = json.loads(database.read())
for item in jsonList:
item = json.loads(item)
person = Person(item['first'], item['last'])
result.append(person)
return result
view.py
from model import Person
def showAllView(list):
print ('In our db we have %i users. Here they are:' % len(list))
for item in list:
print (item.name())
def startView():
print ('MVC - the simplest example')
print ('Do you want to see everyone in my db?[y/n]')
def endView():
print ('Goodbye!')
controller.py
from model import Person
import view
def showAll():
#gets list of all Person objects
people_in_db = Person.getAll()
return view.showAllView(people_in_db)
def start():
view.startView()
answer = input('Enter y or n')
if answer == 'y':
return showAll()
else:
return view.endView()
if __name__ == "__main__":
start()
Data.txt
[{
"first": "abc",
"last": "xyz"
}]
Please, guide me in this and help me find the error. Thanks in advance.
I have solved the problem myself. The main problem was loading JSON elements twice in model.py, like below:
jsonList = json.loads(database.read())
for item in jsonList:
item = json.loads(item)
Now I have solved it by removing item = json.loads(item).

Functions and Dictionary in Python

def build_dictionary(infile):
count_dict={}
for line in infile:
line=line.strip()
if len(line) and line[0]!="-":
lst=line.split(",")
lastname=lst[0].strip()
for lastname in lst:
if lastname not in count_dict:
count_dict[lastname]=1
else:
count_dict[lastname]=count_dict[lastname]+1
return count_dict
def main():
import os.path
while True:
try:
name1=input("Enter input name:")
infile=open(name1,"r")
result=build_dictionary(infile)
print(result)
break
except:
print("Error in code")
main()
I have this program and I want it to take a file that contains last name,first name, take the last names and see how many times they appear in the dict. the only problem i have is it counts the first lastname then stops, whyy isnt it going through the entire dictionary
Replace your build_dictionary method with this:
def build_dictionary(infile):
count_dict={}
for line in infile:
line=line.strip()
if len(line) and line[0]!="-":
lst=line.split(",")
lastname=lst[0].strip()
if lastname not in count_dict:
count_dict[lastname]=1
else:
count_dict[lastname]=count_dict[lastname]+1
return count_dict

Resources