I have an error that I can not get my head around. The code is as follows:
def saveData():
filename = input("Filename to save: ")
print("Saving Data...")
outFile = open(filename, "wt")
for x in team.keys():
name = team[x].getname()
phone = team[x].getphone()
jersey = team[x].getjersey()
outFile.write
(name+", "+phone+", "+jersey+"\n")
print("Data saved.")
outFile.close()
def loadData():
self = {}
filename = input("Filename to load: ")
inFile = open(filename, "rt")
print("Loading data...")
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine[:-1]
name, phone, jersey = inLine.split(", ")
team[name] = self(name, phone, jersey)
print("Data Loaded Successfully.")
inFile.close()
return self
class teamClass:
name = ""
phone = 0
jersey = 0
def __init__(self, name, phone, jersey):
self.name = name
self.phone = phone
self.jersey = jersey
def setName(self, name):
self.name = name
def setPhone(self, phone):
self.phone = phone
def setJersey(self, jersey):
self.jersey = jersey
def getName(self, name):
return name
def getPhone(self, phone):
return phone
def getJersey(self, jersey):
return jersey
def displayData(team):
print("\n")
print("Welcome to the Team Manager")
print("---------------------------")
print("Name: ", team.name)
print("Phone #: ", team.phone)
print("Jersey #: ", team.jersey)
print("\n")
def displayMenu():
print("--------Main Menu--------")
print("\n1. Display Team")
print("2. Add Member")
print("3. Remove Member")
print("4. Edit Member")
print("9. Exit Program")
print("\n")
return int(input("Selection: "))
def printTeam(team):
if len(team) == 0:
print("No team members in memory.")
else:
for x in team.keys():
team.displayData()
def addTeam(team):
newName = input("Enter the new player name: ")
newPhone = input("Enter the phone #: ")
newJersey = input("Enter the jersey #: ")
team[newName] = teamClass(newName, newPhone, newJersey)
return team
def removeTeam(team):
removeName = input("Enter the member to be removed: ")
if removeName in team:
del team[removeName]
else:
print("Team member not found.")
return team
def editTeam(team):
oldName = input("Enter the player you want to edit: ")
if oldName in team:
newName = input("Enter the new name: ")
newPhone = input("Enter the new phone number: ")
newJersey = input("Enter the jersey #: ")
else:
print("Team member not found")
return team
print("Welcome to the Team Manager")
loadData()
team = {}
menuSelection displayMenu()
while menuSelection != 9:
if menuSelection == 1:
printTeam(team)
elif menuSelection == 2:
team = addTeam(team)
elif menuSelection == 3:
team = removeTeam(team)
elif menuSelection == 4:
team = editTeam(team)
menuSelection = displayMenu()
saveData()
print("Exiting Program...")
I get this error once I add a member and try to display the dictionary:
Traceback (most recent call last):
File "C:/Users/Gameradvocat3/PycharmProjects/Week6/Week6.py", line 121, in <module>
printTeam(team)
File "C:/Users/Gameradvocat3/PycharmProjects/Week6/Week6.py", line 83, in printTeam
team.displayData()
AttributeError: 'dict' object has no attribute 'displayData'
Thank you all! I can not figure this out, this is for my Programming Essentials class. The only reason I am reaching out is because I have combed through the code and the literature from class and I can not figure out why this is not working.
The class teamClass has no function displayData() you are calling printTeam() from your menu-screen with a dictionary of teamClass-objects:
def printTeam(team):
if len(team) == 0:
print("No team members in memory.")
else:
for x in team.keys():
displayData(team[x]) # not team.displayData() - thats a class method call
In case you want to make it a class method you need to indent it and give it a first param of self but then other parts of your code need to be adjusted as the method currently is not fit to be a class-function.
I corrected all errors that hindered you from running this. The fixes are minimal effort on my side and lots of stuff could be made neater - ask on codereview for that. Look / ggogle / search SO for python csv - thats better for reading/writing csv data then what you did manually.
def saveData(team):
filename = input("Filename to save: ")
if not filename: # fix for non.input
filename = "temp.csv"
print("Saving Data...")
with open(filename, "wt") as outFile: # with paradigma for file
for x in team.keys():
name = team[x].name # spelling error
phone = team[x].phone # spelling error
jersey = team[x].jersey # spelling error
outFile.write(name + ", " + phone + ", " + jersey + "\n")
print("Data saved.")
def loadData():
d = {} # do not use self , you could buts bad habit
filename = input("Filename to load: ")
if not filename: # if no name given, dont load, return empty
return {}
with open(filename, "rt") as inFile: # with paradig for open
print("Loading data...") # look into module csv
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine[:-1]
name, phone, jersey = inLine.split(", ")
d[name] = teamClass(name, phone, jersey)
print("Data Loaded Successfully.")
return d
class teamClass:
name = ""
phone = 0
jersey = 0
def __init__(self, name, phone, jersey):
self.name = name
self.phone = phone
self.jersey = jersey
# youre not using getters/setters consistently so I removed them
# def setName(self, name):
# self.name = name
# your getters were wrong, fix like this:
# def getName(self): # fix, getter needs no name
# return self.name # fix missing self.
def displayData(player): # renamed - not a team
print("\n")
print("Welcome to the Team Manager")
print("---------------------------")
print("Name: ", player.name)
print("Phone #: ", player.phone)
print("Jersey #: ", player.jersey)
print("\n")
def displayMenu():
print("--------Main Menu--------")
print("\n1. Display Team")
print("2. Add Member")
print("3. Remove Member")
print("4. Edit Member")
print("9. Exit Program")
print("\n")
try: # catch errors
return int(input("Selection: "))
except:
return -1 # will lead to no action and reprint
def printTeam(team):
if len(team) == 0:
print("No team members in memory.")
else:
for x in team.keys():
displayData(team[x]) # fix -print each player of this team
def addTeam(team):
newName = input("Enter the new player name: ")
newPhone = input("Enter the phone #: ")
newJersey = input("Enter the jersey #: ")
team[newName] = teamClass(newName, newPhone, newJersey)
return team
def removeTeam(team):
removeName = input("Enter the member to be removed: ")
if removeName in team:
team.pop(removeName) # remove with pop
else:
print("Team member not found.")
return team
def editTeam(team):
oldName = input("Enter the player you want to edit: ")
if oldName in team:
newName = input("Enter the new name: ")
newPhone = input("Enter the new phone number: ")
newJersey = input("Enter the jersey #: ")
team.pop(oldName) # remove old
team[newName] = teamClass(newName, newPhone, newJersey) # add new
else:
print("Team member not found")
return team
print("Welcome to the Team Manager")
team = loadData()
menuSelection = displayMenu() # = missing
while menuSelection != 9:
if menuSelection == 1:
printTeam(team)
elif menuSelection == 2:
team = addTeam(team)
elif menuSelection == 3:
team = removeTeam(team)
elif menuSelection == 4:
team = editTeam(team)
menuSelection = displayMenu()
saveData(team) # data missing
print("Exiting Program...")
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 days ago.
Improve this question
The problem I am getting is that the file I'm reading, searching, deleting does not exist on the "grocery_note". the code that I need to fix is the .csv file that cannot locate on the computer.
Here is my code:
import os
import re
import csv
from pathlib import Path
print("Welcome to the PDI!")
print("\nWhich stands for PERSONA DETAILS INTERACTIONS")
# Getting the information of the user first before starting the main program.
class Persona:
def __init__(self, Firstname, Middlename, Lastname, Age, Gender, Civil_status, Phone_Number, Telephone_Number, Email_Address, Religion, Language_use, Country, City, Province, Postcode, Street_Name):
self.Firstname = Firstname
self.Middlename = Middlename
self.Lastname = Lastname
self.Age = Age
self.Gender = Gender
self.Civil_status = Civil_status
self.Phone_Number = Phone_Number
self.Telephone_Number = Telephone_Number
self.Email_Address = Email_Address
self.Religion = Religion
self.Language_use = Language_use
self.Country = Country
self.Province = Province
self.City = City
self.Postcode = Postcode
self.Street_Name = Street_Name
# Displaying the user's information
def display_info(self):
print("\nUser's Details:")
print(f"Name: {self.Firstname} {self.Middlename} {self.Lastname}")
print(f"Age: {self.Age} years old")
print(f"Gender: {self.Gender}")
print(f"Civil Status: {self.Civil_status}")
print(f"Phone Number: {'0' + str(self.Phone_Number)}")
print(f"Telephone Number: {self.Telephone_Number}")
print(f"Email Address: {self.Email_Address}")
print(f"Religion: {self.Religion}")
print(f"Language Use: {self.Language_use}")
address = ', '.join([self.Country, self.City + " City", self.Province + " Province", self.Postcode, self.Street_Name])
print(f"Address: {address}")
print()
print("="*30)
a = input("Enter your First Name: ")
x = input("Enter your Middle Name: ")
v = input("Enter your Last Name: ")
b = int(input("Enter your Age: "))
c = input("Enter your Gender (M/F): ")
o = input("Enter your Civil Status: ")
d = int(input("Enter your Phone Number: "))
e = int(input("Enter your Telephone Number: "))
f = input("Enter your Email Address: ")
g = input("Enter your Religion: ")
h = input("Enter your Language Use: ")
i = input("Enter your Country: ")
j = input("Enter your City: ")
k = input("Enter your Province: ")
l = input("Enter your Postcode: ")
m = input("Enter your Street Address: ")
person = Persona(a, x, v, b, c, o, d, e, f, g, h, i, j, k, l, m)
person.display_info()
def create_grocery_file(filepath):
file_path.parent.mkdir(parents=True, exist_ok=True)
with open(file_path, "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Item Name", "Quantity"])
class BankAccount:
def __init__(self, Name, Account_Number, Balance):
self.Name = Name
self.Account_Number = Account_Number
self.Balance = int(Balance)
self.filename = None
def Card(self):
return input("\nDo you want to Enter your Card? (Y/N): ")
def deposit(self, amount):
self.Balance += amount
print(f"\n{str(amount)} was deposited to your account.")
def display_info(self):
return f"\nName: {self.Name}\nAccount Number: {self.Account_Number}\nBalance: {self.Balance}"
def set_filename(self, filename):
self.filename = filename
def write_file(self,text):
with open(self.filename, "w") as f:
f.write(text)
if __name__ == "__main__":
print("\n")
print("=" * 50)
print("\n")
print("="*30)
print("Main Menu")
print("="*30)
print("1. Go to Semi-bank Account ATM")
print("2. Create a note for your Grocery")
print("3. Exit")
print("="*30)
selection = input("\nSelect a number that you want to go: ")
Name1 = input("\nEnter your Name: ")
Account_Number = input("Enter your Pin Number: ")
Balance = input("Enter your Balance: ")
bank_accountsu = BankAccount(Name1,Account_Number,Balance)
bank_accountsu.set_filename("Info of your bank account.txt")
text = bank_accountsu.display_info()
bank_accountsu.write_file(text)
while True:
if selection == "1":
if bank_accountsu.Card().lower() == "y":
print("Your Card is inserted in the Semi-Bank Account ATM")
elif bank_accountsu.Card().lower() == "n":
print("Thank you! for using the Semi-Bank Account ATM")
break
else:
pass
print("\n")
print("="*30)
print("Welcome to Semi-bank Account ATM!")
print("="*30)
print("1. Withdraw")
print("2. Deposit")
print("3. Personal Data Account")
print("4. Exit")
print("="*30)
while True:
option = input("\n Select a Number: ")
if option == "1":
amount = int(input("Enter the amount you want to withdraw: "))
if amount > bank_accountsu.Balance:
print("Insufficient Balance")
else:
bank_accountsu.Balance =- amount
print(f"You have successfully withdraw the amount of {str(amount)}. Your remaining balance is {str(bank_accountsu.Balance)}")
elif option == "2":
amount = int(input("\nEnter the amount you want to deposit: "))
bank_accountsu.deposit(amount)
elif option == "3":
print(bank_accountsu.display_info())
else:
print("\nThank you for using Semi-Bank Account ATM!")
exit()
break
if selection == "2":
grocery_note = input("Enter the name of your grocery note file: ")
file_path = Path.cwd() / "Grocery Notes" / f"{grocery_note}.csv"
file_exists = file_path.exists()
if not file_exists:
file_path.parent.mkdir(parents=True, exist_ok=True)
with open(file_path, "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Item Name", "Quantity"])
while True:
print("\n")
print("="*30)
print("\nWhat would you like to do with your grocery note?")
print("1. Write to grocery note")
print("2. Read grocery note")
print("3. Search grocery note")
print("4. Delete grocery note")
print("5. Exit grocery note")
option = input("\nEnter your choice: ")
if option == "1":
if file_exists:
print(f"Appending to existing file {grocery_note}.csv")
with open(file_path, "a", newline="") as file:
writer = csv.writer(file)
else:
print(f"Creating new file {grocery_note} in Grocery Notes")
file_path.parent.mkdir(parents=True, exist_ok=True)
with open(file_path, "w", newline="") as file:
writer = csv.writer(file)
item = input("Enter the item you want to add to: ")
quantity = input("Enter the quantity:")
with open(file_path, "a", newline="") as file:
writer = csv.writer(file)
writer.writerow([item, quantity])
print("Item added to the grocery note.")
elif option == "2":
if file_exists:
with open(file_path, "r",newline="") as file:
reader = csv.reader(file)
for row in reader:
print(row)
else:
print(f"File {grocery_note} does not exist.")
elif option == "3":
if file_exists:
with open(os.path.join(os.path.expanduser("~"), "Downloads", f"{grocery_note}.csv"), "r") as file:
reader = csv.reader(file)
search_term = input("Enter the item name you want to search: ")
for row in reader:
if search_term.lower() in row[0].lower():
print(row)
found = True
if not found:
print(f"No items found that match {search_term}.")
else:
print(f"File {grocery_note} does not exist.")
elif option == "4":
if file_exists:
os.remove(file_path)
print(f"File {grocery_note} has been deleted.")
else:
print(f"File {grocery_note} does not exist.")
elif option == "5":
print("Thank you for using PDI!")
exit()
break
else:
print("Invalid input.")
[enter image description he(https://i.stack.imgur.com/Xmvo5.png)enter image description here
Here is the problem that says "file does not exist"
Fix the code that I am getting
lstEmployees = []
lstNames = []
counter = 0
def export_employee():
for employee in lstEmployees:
with open("file.txt", "w") as output:
output.write(str(lstEmployees))
def search_uen():
uen = input("Enter employee UEN: ")
for employee in lstEmployees:
if uen == employee[1]:
print("-----------------" + employee[0] + "------------------------")
print("UEN: " + employee[1])
print("Phone: " + employee[2])
print("Email: " + employee[3])
print("Salary: £" + employee[4])
return employee
return -1
def edit_employee():
search = search_uen()
if search == -1:
print("Employee not found...")
else:
name = input("Enter the new name of the employee: ")
uen = input("Enter the new UEN of the employee: ")
phone = input("Enter the Phone number of the employee: ")
email = input("Enter the email of the employee: ")
salary = input("Enter the salary of the employee: ")
search[0] = name
search[1] = uen
search[2] = phone
search[3] = email
search[4] = salary
def add_employee():
global counter
while counter < 5:
print("----------------------------------------------------------\n")
print(" Number of employee ({0:d})" .format(counter))
print("----------------------------------------------------------\n")
name = input("enter employee name: ")
lstNames.insert(counter, name)
uen = input("enter employee UEN: ")
phone = input("enter employee phone number: ")
email = input("enter employee email: ")
salary = input("enter employee salary: ")
lstEmployees.append([name, uen, phone, email, salary])
if counter > 5:
break
else:
continue
def print_employee():
for employee in lstEmployees:
print("-----------------" + employee[0] + "------------------------")
print("UEN: " + employee[1])
print("Phone: " + employee[2])
print("Email: " + employee[3])
print("Salary: £" + employee[4])
def menu():
while True:
print('-------------------------------------------\n')
print('Welcome to the Employee Management System -\n')
print('-------------------------------------------\n')
print('[1] Add An Employee: \n')
print('[2] View All Employees: \n')
print('[3] Search Employees By UEN: \n')
print('[4] Edit Employees Information: \n')
print('[5] Export Employee Records: \n')
user_option = input("Please select an option ")
if user_option == "1":
add_employee()
elif user_option == "2":
print('\n' * 3)
print_employee()
print('\n' * 3)
elif user_option == "3":
found = search_uen()
if found == -1:
print("Employee not found...")
elif user_option == "4":
edit_employee()
elif user_option == "5":
export_employee()
else:
print("Please select valid option...")
if __name__ == "__main__":
menu()
i have no idea what to do here, on line its saying that the variable 'employee' is not used and i dont know why and when i switch the code to make the add_employee function look like this: (see image)code line 7 change
when i run the code i cant add employees and the string will always say 0 even after i have add details in.
other info: im using both latest version of pycharm and python sdk.
You're calling the main() function but there's no main function defined. I think you want to use menu().
Your if __name__ block should look like this:
if __name__ == "__main__":
menu()
Your export_employee function never uses the employee variable in the loop. Every time you just write out the entire list of employees. Below, we open the file before we iterate over the list.
def export_employee():
with open("file.txt", "w") as output:
for employee in lstEmployees:
output.write(str(employee))
This code has an error on the load function but I don't understand what is causing it. I'm importing the class definition from another file, the program does save the file as a text in my computer and the program tells me that it loads the data but when I try to call for a display of the data that's when I'm getting the error.
from roster2 import rosterClass
outFile = open("c:\roster.txt", "wt")
outFile.write("The text and data will be save as a file on c:\roster.txt")
outFile.close()
inFile = open("c:\roster.txt", "rt")
contents = inFile.read()
print (contents)
def saveData(roster):
filename = input("Enter file name:")
print("Saving file.....")
outFile = open(filename, "wt")
for x in roster.keys():
name = roster[x].getname()
phone = roster[x].getphone()
jersey = str(roster[x].getjersey())
outFile.write(name+","+phone+","+jersey+"\n")
print("File saved.")
outFile.close()
def loadData():
roster = {}
filename = input("Enter file to load: ")
inFile = open(filename, "rt")
print("Loading data......")
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine[:-1]
name, phone, jersey = inLine.split(",")
roster[name] = name, phone, jersey
print("Roster data loaded succesfully")
inFile.close()
return roster
def displayMenu():
print ("======Main Menu======")
print ("1. Display roster ")
print ("2. Add player:")
print ("3. Remove player: ")
print ("4. Edit player information.")
print ("5. Save data.")
print ("6. Load data.")
print ("9. Exit Program")
print ("")
return int(input("Select a number to continue: "))
def printRoster(roster):
if len(roster) == 0:
print ("no current players in roster")
else:
for x in roster.keys():
roster [x].displayData()
def addRoster (roster):
newName = input("Enter new player's name:")
newPhone = input("Player's phone number: ")
newJersey = int(input("Player's jersey number:"))
roster[newName] = rosterClass (newName, newPhone, newJersey )
return roster
def removeRoster(roster):
removeName = input("enter player's name to be removed:")
if removeName in roster:
del roster[removeName]
else:
print("player not found in list.")
return roster
def editroster(roster):
oldName = input("Enter the name of the player you want to edit:")
if oldName in roster:
newName = input ("Enter the new player's name:")
newPhone = input("Player's new phone number:")
newJersey = int(input("Player's new jersey number:"))
roster[oldName] = rosterClass (newName, newPhone, newJersey)
else:
print ("no player exist in roster")
return roster
print ("Welcome to the Roster Manager")
roster = {}
menuSelection = displayMenu()
while menuSelection !=9:
if menuSelection == 1:
printRoster(roster)
elif menuSelection == 2:
roster = addRoster(roster)
elif menuSelection == 3:
roster = removeRoster(roster)
elif menuSelection == 4:
roster = editRoster(roster)
elif menuSelection == 5:
roster = saveData(roster)
elif menuSelection == 6:
roster = loadData()
menuSelection = displayMenu()
print ("Goodbye......")
I have taken the liberty of attempting to correct the indentation of your code so that it compiles. Of course it won't run on my computer because I don't have the code that your code imports. However, the diagnostic message you supplied complains that, in ' line 62, in printRoster roster [x].displayData() AttributeError: 'tuple' object has no attribute 'displayData''.
The only place in your code that displayData appears is in this line of code:
roster [x].displayData()
It matches the error message! The message says that roster[x] is a tuple which raises my curiosity. How is roster[x] defined?
Two different ways:
roster[name] = name, phone, jersey
roster[newName] = rosterClass (newName, newPhone, newJersey )
I've been programming for nearly fifty years, I can guess which way is correct. What do you think?
In class we have to create a save/load function utilizing the split() method for a class and dictionary. I managed to get the save function working, but the load function does not seem to want to work for me. I either get it almost working but the saved file does not load, or i get the error
"playerclass" has no "player" attribute. needs to use the init method. Here is the code in its entirety def loaddata(): is mainly the area of concern.
class playerclass:
name = ""
phone = ""
jersey = ""
def __init__(self, name, phone, jersey):
self.name = name
self.phone = phone
self.jersey = jersey
def setname(self, name):
self.name = name
def setphone(self, phone):
self.phone = phone
def setjersey(self, jersey):
self.jersey = jersey
def getname(self):
return self.name
def getphone(self):
return self.phone
def getjersey(self):
return self.jersey
def disroster(self):
print("Player Bio")
print("-----------")
print("Name: ", self.name)
print("Phone #: ", self.phone)
print("Jersey #: ", self.jersey)
def savedata (players):
filename = input("Enter file name: ")
print("Saving....")
outFile = open(filename, "wt")
for x in players.keys():
name = players[x].getname()
phone = str(players[x].getphone())
jersey = str(players[x].getjersey())
outFile.write(name+","+phone+","+jersey+"\n")
print("Save Complete")
outFile.close()
def loaddata ():
players = {}
filename =input("Enter filename to load: ")
inFile = open(filename, "rt")
print("Loading.....")
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine [:-1]
name, phone, jersey = inLine.split(",")
players[name] = playerclass(name, phone, jersey)
print("Load Successfull.")
inFile.close()
return players
def roster(players):
if len(players) == 0:
print("No players on roster: ")
else:
for x in players.keys():
players[x].disroster()
def add_player (players):
newName=input("Enter name of player to add: ")
newPhone = int(input("Enter phone number of player: "))
newJersey = int(input("Enter number of assigned jersey: "))
players[newName]= playerclass(newName, newPhone, newJersey)
return players
def ed_player (players):
oldName = input("Enter players name to edit: ")
if oldName in players:
newName = input("Enter new name for player: ")
newPhone = int(input("Enter new phone number for player: "))
newJersey = int(input("Enter newly assigned jersey number: "))
players[oldName] = playerclass(newName, newPhone, newJersey)
return players
def del_player(players):
delName = input("Enter players name to delete from roster: ")
if delName in players:
del players[delName]
return players
def displayMenu():
print("-------Main Menu-------")
print("1. Display Team Roster.")
print("2. Add Member.")
print("3. Remove Member.")
print("4. Edit Member.")
print("5. Save Data.")
print("6. Load Data.")
print("9. Exit Program.")
return input("Menu Choice: ")
print("Team Management Tools.")
players = {}
menu_choice = displayMenu()
while menu_choice != '9':
if menu_choice == '1':
roster(players)
elif menu_choice == '2':
players = add_player (players)
elif menu_choice == '3':
players = del_player (players)
elif menu_choice == '4':
players = ed_player (players)
elif menu_choice == '5':
savedata (players)
elif menu_choice == '6':
loaddata ()
menu_choice = displayMenu()
print("Updating roster Goodbye:")
Remove players = {} from your loaddata function, and it'll load properly.
If you actually want to reset the contents of the dictionary when loading (which might have been your intent, although I would say that's a questionable design decision), you can do:
def loaddata():
global players
players = {}
...
This is because any variables you write to are assumed to be local variables (as in, local to the function) unless you say otherwise.
I might be overlooking something, but I'm not seeing anything that attempts to read a player attribute from any object, so I'm not sure where the error is coming from. Was it from a different version of this code? Or, if it is the posted version that has that error, can you provide exactly what series of inputs lead to the error?
The rest of this answer isn't directly relevant to your question, just some tips based on things I noticed in your code.
I would remove the:
name = ""
phone = ""
jersey = ""
Because you set them in __init__ and so they're redundant and not doing anything. For looping over lines in files, you can use a for loop, which is more readable than while loops. Example:
for line in infile:
print(line)
And you should look into with. It's another type of block, and they're very useful when working with files because they'll automatically close the file when the block ends, so you don't have to. As an example:
with open("foo", "r") as stream:
for line in stream:
print(line)
# stream got implicitly closed because the block ended
Ill keep this brief. I have a Python class file and a regular file.
The class is student and the point of the program is be able to change some attribute, add a student and display GPA after you in a student.
here is the Program file:
import studentClass
import pickle
student = studentClass.Student
FILENAME = "students.dat"
LOOK_UP = 1
ADD = 2
CHANGE_GPA = 3
CHANGE_GRADE = 4
DISPLAY = 5
QUIT = 6
#makes Students
def make_students():
print("Enter data for students")
output_file = open(FILENAME, "wb")
for count in range(1,2):
print("Student " +str(count) + ':')
name = input("Enter student Name: ")
stuID = int(input("Enter student ID:"))
GPA = float(input("Enter GPA: "))
expectGrade = (input("Enter the expected grade: "))
fTime_pTime = input("Is the student full-time or part-time: ")
student(name,stuID, GPA, expectGrade, fTime_pTime)
pickle.dump(student, output_file)
output_file.close()
main()
#Shows GPA of student
def showGPA(students):
name = input("enter a name: ")
if name in students:
entry = student.get_GPA()
print(entry)
#adds and student
def add(students):
name = input("Enter student Name: ")
stuID = int(input("Enter student ID:"))
GPA = float(input("Enter GPA: "))
expectGrade = (input("Enter the expected grade: "))
fTime_pTime = input("Is the student full-time or part-time: ")
entry = student(name,stuID, GPA, expectGrade, fTime_pTime)
if name not in students:
students[name] = entry
print('Entry has been added')
else:
print('That name is taken')
#Changes GPA
def changeGPA(students):
name = input("Enter a name: ")
if name in students:
GPA = input("enter a new GPA")
entry = student.set_GPA(GPA)
students[name] = entry
print("Info updated")
else:
print("That name was not found")
#Changes expected grade
def changeEX(students):
name = input("Enter a name: ")
if name in students:
expectGrade = input("enter a new GPA")
entry = student.set_expectGrade(expectGrade)
students[name] = entry
print("Info updated")
else:
print("That name was not found")
#Saves changes
def save_students(student):
output_file = open(FILENAME, 'wb')
pickle.dump(student, output_file)
output_file.close()
#Displays list of students
def display_list(student_list):
for item in student_list:
print(item.get_name())
print(item.get_stuID())
print(item.get_GPA)
print(item.get_expectGrade)
print(item.get_fulltime)
#Loads the students.dat
def load_students():
try:
input_file = open(FILENAME, 'rb')
student_dct = pickle.load(input_file)
input_file.close()
except IOError:
student_dct = {}
return student_dct
def make_menu():
print("1. Look up Students GPA.")
print("2. Add a new student.")
print("3. Change GPA for a student.")
print("4. Change expected grade of a student")
print("5. Display all student.")
print("6. Quit Program.")
choice = int(input("Enter your choice: "))
while choice < LOOK_UP or choice > QUIT:
choice = int(input("Enter a vaild choice: "))
return choice
def main():
#pickle_student.main()
#make_students()
studentObjs = load_students()
choice = make_menu()
while choice != QUIT:
if choice == LOOK_UP:
showGPA(studentObjs)
elif choice == ADD:
add(studentObjs)
elif choice == CHANGE_GPA:
changeGPA(studentObjs)
elif choice == CHANGE_GRADE:
changeEX(studentObjs)
elif choice == DISPLAY:
display_list(studentObjs)
save_students(studentObjs)
#runs program
make_students()
AND...the class file
__author__ = 'MichaelCorbett'
class Student:
def __init__(self,name,stuID, GPA, expectGrade, fulltime):
self.__name = name
self.__studID = stuID
self.__GPA = GPA
self.__expectGrade = expectGrade
self.__fulltime = fulltime
# Set methods
def set_name(self,name):
self.__name = name
def set_stuID(self, stuID):
self.__studID
def set_GPA(self, GPA):
self.__GPA = GPA
def set_expectGrade(self, expectGrade):
self.__expectGrade
def set_fulltime(self, fulltime):
self.__fulltime = fulltime
# Get methods
def get_name(self):
return self.__name
def get_stuID(self):
return self.__studID
def get_GPA(self):
return self.__GPA
def get_expectGrade(self):
return self.__expectGrade
def get_fulltime(self):
return self.__fulltime
def __str__(self):
return "Student: " + self.__name + \
"\nStudent ID: " + self.__studID+ \
"\nGPA: "+ self.__GPA+ \
"\nExpected Grade: " + self.__expectGrade+\
"\nFullTime: " + self.__fulltime
ERROR:
Traceback (most recent call last):
File "/Users/MichaelCorbett/PycharmProjects/lab9/test.py", line 171, in <module>
make_students()
File "/Users/MichaelCorbett/PycharmProjects/lab9/test.py", line 37, in make_students
main()
File "/Users/MichaelCorbett/PycharmProjects/lab9/test.py", line 165, in main
display_list(studentObjs)
File "/Users/MichaelCorbett/PycharmProjects/lab9/test.py", line 110, in display_list
for item in student_list:
TypeError: 'type' object is not iterable
In your function make_students(), don't pickle the class student:
student(name,stuID, GPA, expectGrade, fTime_pTime)
pickle.dump(student, output_file)
Pickle the created instances:
one_student = student(name,stuID, GPA, expectGrade, fTime_pTime)
pickle.dump(one_student, output_file)
It is better to keep the class capitalized:
from studentClass import Student
now you can write :
student = Student(name,stuID, GPA, expectGrade, fTime_pTime)
pickle.dump(student, output_file)
By convention classes a capitalized and instance are lowercase. This helps to understand what is going on.