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?
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
I am a student and have a task to create a contact book with usage of oop, functions, txt file , import os.
I just decided to create a book with usage of functions and txt file.
And ...I have faced with some problem of deleting the indicated line (record) in txt file. I have tried many variations of how to do it. Result: delete an all information in the file or just last line, or simply read file and thats all. All I need is to delete a record as per indicated input(word/name).
my tutor edvised me to use a del function :
if each_contact.name==name:
del list_contacts[i]
but i have no idea how to use this function at all. What the logic should be?
my code is like:
def del_contact_name():
## It should delete the required line as per name if txt file
del_name=input('Enter first name for delete this contact record: ')
del_name=del_name.title()
with open(file_name, "r") as f:
file_delete = f.readlines()
with open(file_name, "w") as f:
for line in file_delete:
if line != del_name:
f.write(line)
print("Your Required Contact Record is deleted:", end=" ")
break
and this is just delete only last line if I write a 3 lines of records ( it works, but i need another result). If I do an one record it will not delete but read the line.
The full work looks like this:
file_name = "phonebook.txt"
filerec = open(file_name, "a+")
filerec.close
def show_main_menu():
## General menu
print("\n Phone Book \n"+
" my task and projects \n"+
"=================================\n"+
"Enter 1,2,3,4 or 5:\n"+
" 1 To Display Contacts Records\n" +
" 2 To Add a New Contact Record\n"+
" 3 To Search Contacts\n"+
" 4 To Delete Contacts\n"+
" 5 To Quit\n=========================")
choice = input("Enter your choice: ")
if choice == "1":
filerec = open(file_name, "r+")
file_contents = filerec.read()
if len(file_contents) == 0:
print("Phone Book is Empty")
else:
print (file_contents)
filerec.close
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice == "2":
enter_contact_record()
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice == "3":
search_contact_record()
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice=='4':
del_contact_name()
entry=input("Press Enter to continue ...")
show_main_menu()
elif choice== "5":
print("Thanks for using Phone Book Programm ")
else:
print("Wrong choice, Please Enter [1 to 5]\n")
entry = input("Press Enter to continue ...")
show_main_menu()
def search_contact_record():
##' This function is used to searches a specific contact record
search_name = input("Enter First name for Searching contact record: ")
search_name = search_name.title()
filerec = open(file_name, "r+")
file_contents = filerec.readlines()
found = False
for line in file_contents:
if search_name in line:
print("Your Searched Contact Record is:", end=" ")
print (line)
found=True
break
if found == False:
print("There's no contact Record in Phone Book with name = " + search_name )
def enter_contact_record():
## It collects contact info firstname, last name, notes and phone
first = input('Enter First Name: ')
first = first.title()
last = input('Enter Last Name: ')
last = last.title()
phone = input('Enter Phone number: ')
notes = input('Enter notes: ')
contact = ("[" + first + " " + last + ", " + phone + ", " + notes + "]\n")
filerec = open(file_name, "a")
filerec.write(contact)
print( "This contact\n " + contact + "has been added successfully!")
def del_contact_name():
## It should delete the required line as per name in txt file
del_name=input('Enter first name for delete this contact record: ')
del_name=del_name.title()
with open(file_name, "r") as f:
file_delete = f.readlines()
with open(file_name, "w") as f:
for line in file_delete:
if line != del_name:
f.write(line)
print("Your Required Contact Record is deleted:", end=" ")
break
show_main_menu()
file_name = "phonebook.txt"
def show_main_menu():
## General menu
print("\n Phone Book \n"+
" my task and projects \n"+
"=================================\n"+
"Enter 1,2,3,4 or 5:\n"+
" 1 To Display Contacts Records\n" +
" 2 To Add a New Contact Record\n"+
" 3 To Search Contacts\n"+
" 4 To Delete Contacts\n"+
" 5 To Quit\n=========================")
choice = input("Enter your choice: ")
if choice == "1":
show_file()
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice == "2":
add_file()
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice == "3":
search_file()
entry = input("Press Enter to continue ...")
show_main_menu()
elif choice=='4':
dell_file()
entry=input("Press Enter to continue ...")
show_main_menu()
elif choice== "5":
print("Thanks for using Phone Book Programm ")
else:
print("Wrong choice, Please Enter [1 to 5]\n")
entry = input("Press Enter to continue ...")
show_main_menu()
def initials():
first = input('Enter First Name: ')
first = first.title()
last = input('Enter Last Name: ')
last = last.title()
phone = input('Enter Phone number: ')
notes = input('Enter notes: ')
contact = ("[" + first + " " + last + ", " + phone + ", " + notes + "]\n")
return contact
def show_file():
#show file
filerec = open(file_name, "r+")
file_contents = filerec.read()
if len(file_contents) == 0:
print("Phone Book is Empty")
else:
print (file_contents)
filerec.close()
def add_file():
#add text to a file
with open(file_name, 'a') as f:
f.write(initials())
f.close()
def search_file():
##' This function is used to searches a specific contact record
search_name = input("Enter First name for Searching contact record: ")
# If you enter not a name, but a sign that is in the record, then he will find it
search_name = search_name.title()
filerec = open(file_name, "r+")
file_contents = filerec.readlines()
found = True
for line in file_contents:
if search_name in line:
print("Your Searched Contact Record is:", end=' ')
print (line)
found=False
break
if found:
print("There's no contact Record in Phone Book with name = " + search_name )
filerec.close()
def dell_file():
## It should delete the required line as per name in txt file
del_name=input('Enter first name for delete this contact record: ')
del_name=del_name.title()
count_str = 0
no_string = True
with open(file_name, "r+") as file:
lines = file.readlines()
for i in lines:
count_str +=1
if del_name in i:
no_string = False
del lines[count_str-1]
break
if no_string:
print('No line')
with open(file_name, "w") as file:
file.writelines(lines)
file.close()
show_main_menu()
Now the deletion is working.
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...")
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
I am currently developing a program for my local charity and would like to ask how to get the program to
1) Search a notepad file for a specific Word(s)
2) Store which line that the name was found on
My code so far :
import time
def AddToDatabase():
print ("\nYou are adding to the Database. \nA)Continue \nB)Go Back")
ATD = input(": ")
if ATD == "A" or ATD == "a":
Name = input("\nEnter Name of Member [First Name and Surname]: ")
with open("Name.txt", "a") as N:
N.write("\n{}".format(Name))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
print ("\nEnter Address of "+Name+" all on one line")
print ("In format [Include Commas]")
print ("\nRoad name with house number [e.g. 1 Morgan Way], Borough [e.g Harrow], City [e.g London], Postcode [e.g. HA5 2EF]")
Address = input("\n: ")
with open("Address.txt", "a") as A:
A.write("\n{}".format(Address))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
Home_Number = input("\nEnter Home Number of "+Name+": ")
with open("Home Number.txt", "a") as HN:
HN.write("\n{}".format(Home_Number))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
Mobile_Number = input ("\nEnter Mobile Number of "+Name+": ")
with open("Mobile Number.txt", "a") as MN:
MN.write("\n{}".format(Mobile_Number))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
Email_Address = input ("\nEnter Email Address of "+Name+": ")
with open("Email Address.txt", "a") as EA:
EA.write("\n{}".format(Email_Address))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
Dietry_Needs = input("\nEnter Medical/Dietry Needs of "+Name+": ")
with open("Medical Dietry Needs.txt", "a") as MDN:
MDN.write("\n{}".format(Dietry_Needs))
time.sleep(1)
print ("\nAdding...")
time.sleep(1)
print ("All information for "+Name+" has been added. Redirecting Back To Main...")
time.sleep(5)
Main()
elif ATD == "B" or ATD == "b":
Main()
def CheckDatabase():
print ("\nSPACE SAVED")
def Main():
print ("\nSVA of UK Database")
while True:
print ("\nA)Check Database \nB)Add to Database \nC)Exit Program")
choice = input(": ")
if choice == "A" or choice == "a":
CheckDatabase()
elif choice == "B" or choice == "b":
AddToDatabase()
elif choice == "C" or choice == "c":
break
else:
print ("Invalid Input")
Main()
Main()
How would try to search for example 'John Smith' in a txt file and store which line that name was found on? I know i may have maybe come across confusing but if you don't get it then please leave a comment and ill answer what you dont get! Thanks in advance!
Pretty basic...
found_line = None
with open(filename) as f:
pattern = "john smith"
for i, line in enumerate(f):
if pattern in line:
found_line = i
print "Found %s in %i" % (pattern, i)