I currently have this code which works fine, but I need to be able to delete data on command from the data file.
This is what the inside of the file looks like:
[[15, "TomBy012"], [10, "Badrob135"]]
And this is what my code looks like:
import json
def load_scores():
with open("scores.json") as infile:
return json.load(infile)
def save_scores(scores):
with open("scores.json", "w") as outfile:
json.dump(scores, outfile)
print("Scores Saved")
def scoresMenu():
print ("""Please pick a valid option from the list below
1 » Load existing scores from the database
2 » Save the scores from this session
3 » Create a new score for the database
4 » Delete specific scores from the database
""")
menuInput = input(" Option » ")
if menuInput == "3":
global scores
name = input(" Input Your Username » ")
score = int(input("Input Your Score » "))
entry = [score, name]
scores.append(entry)
scores.sort(reverse=True)
scores = scores[:10]
elif menuInput == "1":
print(scores)
elif menuInput == "2":
save_scores(scores)
elif menuInput == "4":
print("Work In Progress!")
else:
print("GoodBye! Thanks for trying our program.")
exit
scores = load_scores()
while True:
print(" ")
scoresMenu()
To sum up, what I want to achieve is if a user inputs, for example, 'Tomby' it would delete the score assosiacted and the name from the file so [15, "TomBy"] would be removed. How would I implement this?
Ask the user for the name to delete
Iterate the list
Delete the item that matches the name
It might look like like this:
#UNTESTED
name = input(" Input Your Username » ")
for index, item in enumerate(scores):
if item[1] == name:
del scores[index]
break
Related
import re
contact = {}
def display_contact():
for name, number in sorted((k,v) for k, v in contact.items()):
print(f'Name: {name}, Number: {number}')
#def display_contact():
# print("Name\t\tContact Number")
# for key in contact:
# print("{}\t\t{}".format(key,contact.get(key)))
while True:
choice = int(input(" 1. Add new contact \n 2. Search contact \n 3. Display contact\n 4. Edit contact \n 5. Delete contact \n 6. Save your contact as a file \n 7. Update Saved List \n 8. Exit \n Your choice: "))
if choice == 1:
while True:
name = input("Enter the contact name ")
if re.fullmatch(r'[a-zA-Z]+', name):
break
while True:
try:
phone = int(input("Enter number "))
except ValueError:
print("Sorry you can only enter a phone number")
continue
else:
break
contact[name] = phone
elif choice == 2:
search_name = input("Enter contact name ")
if search_name in contact:
print(search_name, "'s contact number is ", contact[search_name])
else:
print("Name is not found in contact book")
elif choice == 3:
if not contact:
print("Empty Phonebook")
else:
display_contact()
elif choice == 4:
edit_contact = input("Enter the contact to be edited ")
if edit_contact in contact:
phone = input("Enter number")
contact[edit_contact]=phone
print("Contact Updated")
display_contact()
else:
print("Name is not found in contact book")
elif choice == 5:
del_contact = input("Enter the contact to be deleted ")
if del_contact in contact:
confirm = input("Do you want to delete this contact Yes or No? ")
if confirm == 'Yes' or confirm == 'yes':
contact.pop(del_contact)
display_contact
else:
print("Name is not found in phone book")
elif choice == 6:
confirm = input("Do you want to save your contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
with open('contact_list.txt','w') as file:
file.write(str(contact))
print("Your contact-book is saved!")
else:
print("Your contact book was not saved.")
# else:
elif choice == 7:
confirm = input("Do you want to update your saved contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
f = open("Saved_Contact_List.txt" , "a")
f.write("Name = " + str(name))
f.write(" Number = " + str(phone))
f.close()
#with open('contact_list.txt','a') as file:
# file.write(str(contact))
print("Your contact-book has been updated!")
else:
print("Your contact book was not updated.")
else:
break
I have tried but only get to save the last input and not all of the contact list. Any ideas on how to save them all. I have been trying different code as I have comment some out to try a different way but it only print the last input. I would like it to save a output file with the first save to save all the contact then if they add or update a contact to save it as a updated saved file like choice 7. But I only get it to save the last input. I still learning how python works and this is over my head.
You're looking for serialization, which is (usually) best left to libraries. The json library easily handles reading and writing dictionaries to a file.
To write a dictionary, take a look at json.dump():
with open("Saved_Contact_List.txt", "w") as f:
json.dump(contact, f)
This is the assignment:
The first program will read each player’s name and golf score as keyboard input, then save these as records in a file named golf.txt. (Each record will have a field for the player’s name and a field for the player’s score.)
The second program reads the records from the golf.txt file and displays them.
This is my code so far:
def main():
Continue = 'yes'
golf_file = open('golf.txt', 'a')
while Continue == 'yes':
player_name = input("Input the player's name: ")
player_score = input("Input the player's score: ")
golf_file.write(player_name + "\n")
golf_file.write(str(player_score) + "\n")
Continue = input("Would you like to continue? [yes]: ")
display_file = input("Would you like to display the records from the golf.txt? [yes]: ")
golf_file.close()
if(display_file == 'yes'):
displayfile()
def displayfile():
golf_file = open('golf.txt', 'r')
for line in golf_file:
print("The score of this person is: ",line)
print("The name of this person is: ",line)
golf_file.close()
main()
When the names/scores print it looks like this:
The golf.txt:
You are reading one line (that contains the name), and printing it as the name and the score. Then you read the next line containing a score) and print it as the name and the score again.
You want to alternate treating a line as a name or a score, something like
def displayfile():
with open('golf.txt', 'r') as golf_file:
for name in golf_file:
print("The name of this person is: ", name)
score = next(golf_file)
print("The score of this person is: ", score)
Because golf_file is its own iterator, calling next in the body of the loop advances the file pointer by one line, so that the loop always resumes by reading a name line.
Something a little more symmetric might be
def displayfile():
with open('golf.txt', 'r') as golf_file:
while True:
try:
name = next(golf_file)
score = next(golf_file)
except StopIteration:
break
print("The name of this person is: ", name)
print("The score of this person is: ", score)
Even simpler, though, would be to write each name and score on a single line.
def main():
with open('golf.txt', 'a') as golf_file:
while True:
player_name = input("Input the player's name: ")
player_score = input("Input the player's score: ")
golf_file.write(f"{player_name}\t{player_score}\n")
continue = input("Would you like to continue? [yes]: ")
if continue != 'yes':
break
display_file = input("Would you like to display the records from the golf.txt? [yes]: ")
if display_file == 'yes':
displayfile()
def displayfile():
with open('golf.txt', 'r') as golf_file:
for line in golf_file:
name, score = line.strip().split('\t')
print("The score of this person is: ", name)
print("The name of this person is: ", score)
main()
so i have this project that I should make a program to add identify or delete data from an inventory.txt file
but when I ever try to print the inputs in the file I get messy text, what I'm looking for is a table-like structure printed inputs in the .txt file, I've tried to remove and readjust the place of \n and \t but still, I get stuff like this in the file
Samsung ide445 2154SS rams 120.0 14
Logetech Specture lid224 G502 230.0 8
here's my code for a closer look:
#This function is to get the parts information from the user
def input_parts():
#Taking the parts input from the user
try:
make = input("Enter the make: ")
model = input("Enter the model: ")
part_id = input("Enter part_id: ")
part_name = input("Enter part name: ")
price = float(input("Enter price:QR "))
quantity = int(input("Enter quantity: "))
except ValueError:
print("BOTH PRICE AND QUANTITY CAN NOT BE LETTERS, PLEASE RE-ENTER THE RIGHT DATA")
else:
#transferring both price and quantitiy to strings
price = str(price)
quantity = str(quantity)
list = ['\n'+make,model,part_id,part_name,price,quantity]
return list
#This function is to save the parts information to a file
def add_parts():
#Assignning this sentinal to make the loop repeat if the user didn't want to save
sentinal = True
while sentinal is True:
#Assigning the values of the inputs function to a variable
parts = input_parts()
#Validating user's unput
try:
#Asking the user if he wants to save the information to the file
save = input("Save? (Y/N) or Q to quit ")
except TypeError:
print("YOU CANNOT SAVE WRONG DATA IN THE FILE PLEASE RE-ENTER YOUR DATA")
else:
pass
#A boleen function to export the data to the file if the boleen is true
if save.lower() == 'y':
outfile = open('inventory.txt',"a")
#Validating user's input
try:
#Using a for loop to print the information in the file
for i in parts:
outfile.write(i+'\t')
except TypeError:
print("YOU CAN NOT SAVE WRONG DATA FILES!!!")
break
else:
pass
outfile.close
print("....Record saved.")
sentinal = False
#Using an elif statment to enable the user to re input his data
elif save.lower() == 'n':
sentinal = True
#Using an elif statment to quit if the user wants to
elif save.lower() == 'q':
break
#Using else statment to tell the user no input a valid choice
else:
print("PLEASE ENTER (Y/N) IF YOU WANT TO SAVE!!!!")
print("YOUR DATA HAS NOT BEEN SAVED")
print("PLEASE RE-ENTER YOUR DATA AND TRY AGAIN.")
sentinal = True
add_parts()
You can import tabulate module and use it as below example:
from tabulate import tabulate
print(tabulate([['Saeed', 26], ['You', 24]], headers=['Name', 'Age']))
Result:
Name Age
------ -----
Saeed 26
You 24
You may use this module to reach what you want.
I have taken what was once a class project and turned it into something more usable for work. My program is designed as an inventory system. I have currently ensured that my program can export data to a text file, and import that data at request if the program is ever closed. I cannot edit the data after import unless I add new data to the list first, or add new data to the list then import.
I think the reason why it isn't working is because the data imported from the list doesn't have a logical position yet until new data is added.
class Inventory:
def __init__(self):
self.item = ""
self.amount = 0
self.asset_tag = 0
self.notes = ""
def add_inventory(self):
self.item = input("Enter item: ")
self.amount = int(input("How many? "))
self.asset_tag = int(input("Enter Asset Tag if available. Enter 0 if not tagged. "))
self.notes = input("Please add any additional information: ")
def __str__(self):
return('Item: %s Amount: %d Asset Tag: %d Notes: %s' %
(self.item, self.amount, self.asset_tag, self.notes))
inventory_list = []
def edit(inventory_list):
pos = int(input('Enter the position of the item you would like to edit: '))
new_inventory = item.add_inventory()
new_inventory = item.__str__()
inventory_list[pos-1] = new_inventory
print('Inventory has been updated. If the amount is now 0 please notify.')
while True:
print("""
1. Add new inventory.
2. Remove item from inventory.
3. View inventory.
4. Update current inventory.
5. Export inventory to file.
6. Import Inventory file
7. Quit
""")
ans = input('What would you like to do? ')
if ans == "1":
item = Inventory()
item.add_inventory()
inventory_list.append(item.__str__())
elif ans == "2":
for i in inventory_list:
inventory_list.pop(int(input('Enter position of item to remove: ')))
print('Inventory item removed successfully!')
elif ans == "3":
print('\n'.join(map(str, inventory_list)))
elif ans == "4":
edit(inventory_list)
elif ans == "5":
f = open('Inventory_List.txt', 'w')
for ele in inventory_list:
f.write(ele+'\n')
f.close()
elif ans == "6":
with open('Inventory_List.txt') as f:
data = f.read().splitlines()
print(data)
inventory_list.extend(data)
elif ans == "7":
break
else:
print('Invalid entry, try again.')```
item is not defined in the function edit before it gets utilized.
I need to add to a .csv file based on user input. Other portions of the code add to the file but I can't figure out how to have it add user input. I'm new to python and coding in general.
I have other portions of the code that can merge or draw the data from a .csv database and write it to the separate file, but can't figure how to get it to take multiple user inputs to write or append to the outgoing file.
def manualentry():
stock = input("Enter Stock #: ") #Generate data for each column to fill in to the output file.
VIN = input("Enter Full VIN: ") #Each line asks the user to add data do the line.
make = input("Enter Make: ")
model = input("Enter Model: ")
year = input("Enter Year: ")
l8v = input("Enter L8V: ")
print(stock, VIN, make, model, year, l8v) #Prints the line of user data
input4 = input("Append to inventory list? Y/N") #Asks user to append the data to the output file.
if input4 == "Y" or input4 == "y":
with open('INV.csv','a', newline='') as outfile: #Pull up a seperate csv to write to, an output for collected data
w = csv.writer(outfile) #Need to write the user input to the .csv file.
w.writerow([stock, VIN, make, model, year, l8v]) #<-This is the portion that seems to fall apart.
print("INVENTORY UPDATED")
starter() #Restarts whole program from begining.
if input4 == "N" or input4 == "n":
print("SKIPPING. RESTARTING....")
starter() #Reset
else:
print("Invalid entry restarting program.")
starter() #Reset
starter() #R E S E T !
Just need the user inputs to be applied to the .csv and saved there. Earlier portions of the code function perfectly except this to add to the .csv file. It's to fill in missing data that would otherwise not be listed in a separate database.
Some improvement in the code.
You can use a looping condition like while or for instead of recursion
You can open your csv file at the start of the code instead of doing it everytime
You can come up with a word say stop to stop the loop, close the file and exit
You can use str.lower() == 'y' to cover for both y and Y, upper and lower case
The code will then look like
import csv
def manualentry():
#Open csv file at start
outfile = open('INV.csv', 'a', newline='')
w = csv.writer(outfile) # Need to write the user input to the .csv file.
#Everything wrapped in a while True loop, you can change to any loop accordingly
while True:
stock = input("Enter Stock #: ") # Generate data for each column to fill in to the output file.
VIN = input("Enter Full VIN: ") # Each line asks the user to add data do the line.
make = input("Enter Make: ")
model = input("Enter Model: ")
year = input("Enter Year: ")
l8v = input("Enter L8V: ")
print(stock, VIN, make, model, year, l8v) # Prints the line of user data
input4 = input("Append to inventory list? Y/N") # Asks user to append the data to the output file.
if input4.lower() == "y":
w.writerow([stock, VIN, make, model, year, l8v]) # <-This is the portion that seems to fall apart.
print("INVENTORY UPDATED")
if input4.lower() == "n":
print("SKIPPING. RESTARTING....")
#If you see stop, stop writing, close the file and exit
if input4.lower() == 'stop':
print('Not writing anymore! Stopping')
outfile.close()
exit()
else:
print("Invalid entry restarting program.")
#Call manualentry
manualentry()
You can simply use user input controlled while loop to recursively get user input and then you can exit depending on the user choice
user_input = 'Y'
while user_input.lower() == 'y':
# Run your code here
user_input = input('Do you want to add one more entry: Enter [Y/N]')
Try this
import csv
def boo():
stock = input("Enter Stock #: ") # Generate data for each column to fill in to the output file.
VIN = input("Enter Full VIN: ") # Each line asks the user to add data do the line.
make = input("Enter Make: ")
model = input("Enter Model: ")
year = input("Enter Year: ")
l8v = input("Enter L8V: ")
print(stock, VIN, make, model, year, l8v) # Prints the line of user data
input4 = input(
"Append to inventory list? Y/N || anything else to exit") # Asks user to append the data to the output file.
if input4 == "Y" or input4 == "y":
with open('INV.csv', 'a',
newline='') as outfile: # Pull up a separate csv to write to, an output for collected data
w = csv.writer(outfile)
w.writerow([stock, VIN, make, model, year,
l8v]) # Need to write the previously pulled up line to new csv
print("INVENTORY UPDATED")
user_input = input('Do you want to add one more entry: Enter [Y/N]')
if user_input.lower() == 'y':
boo()
else:
exit()
boo()