How to delete given element from a python dictionary? - python

I am practicing python and doing an exercise where I have to ask for input of different information from patients of a hospital (name, last name, etc) this information has to be saved in a different json file. I managed to do it however I also have to make it so, with an input, I can remove/edit a specific patient from the dictionary (along with all of their info) while keeping the others intact.
I was thinking that maybe I could assign a number to every patient that's added, so this patient can be tracked with the number, however I'm not sure how to code that. I did however made a function to clear everything from the json file, but it has to remove/edit someone specific, not everyone.
My code so far is:
import json
def read_file(file_name):
obj_arch = open(file_name, 'rt', encoding='utf-8')
str_contenido = obj_arch.read()
res = json.loads(str_contenido)
obj_arch.close()
return res
def save_file(file_name, lista):
obj_arch = open(file_name, 'wt', encoding='utf-8')
str_content_to_save = json.dumps(lista)
print(str_content_to_save)
obj_arch.write(str_content_to_save)
obj_arch.close()
opcion = int(input("choose an option: 1 - read. 2 - save"))
if opcion == 1:
lista = read_file('prueba_json.json')
print("Full list:")
print(lista)
else:
lista = read_file('prueba_json.json')
while True:
print("--- PATIENT INFO ---")
Name = input("Input name: ")
Lastname = input("Input lastname: ")
DateB= input("Input date of birht: ")
repeat = input("Do you want to add more info?: ")
clean_file = input("Clean everything from the json file? (yes/no): ")
lista.append({
"Name": Name,
"Lastname": Lastname,
"Date of Birth": DateB
})
if repeat == 'no' or repeat == 'NO':
break
save_file('prueba_json.json',lista)
With this I was able to sabe the patients info in the json file, but how can I write another input like "Insert number of patient to remove or delete" to do that?
In order to clean the whole json file I've done it with this:
def clean_json():
with open('prueba_json.json', 'w') as arc:
arc.writelines(["[{}]"])
if clean_file == "yes" or clean_file == "YES":
clean_json()
Maybe I could adapt some of this to remove or delete someone instead of the whole file?

Related

Save input as text file in python

I got a simple python code with some inputs where a user has to type name, age, player name and his best game.
Now I want that all these inputs from the user were saved as a text file or something like this.
I tried
with open ("Test_", "a") as file:
User_input = file.write(input("here type in your name"))
I tried it with with open ... n where I create a new text file before which I open in python and add something. But everything I tried failed. Hope my English is good enough to understand what kind of problem I have.
import csv
OUTFILE = 'gameplayers.csv'
def main():
player = []
morePlayer = 'y'
while morePlayer == 'y':
name = input('Enter your name: ')
age = input('Your age: ')
playerName = input('Your player name: ')
bestGame = input('What is your best game: ')
player.append([name, age, playerName, bestGame])
morePlayer = input('Enter information of more players: (y, n): ')
with open(OUTFILE, 'a', encoding='utf_8') as f:
csvWriter = csv.writer(f, delimiter=',')
csvWriter.writerows(player)
if __name__ == '__main__':
main()
If you want to keep adding new data, use a otherwise, use w to overwrite. I've used a in this example:
name = input('Name: ')
age = input('Age: ')
best_game = input('Best Game: ')
with open('user_data.txt', 'a') as file:
file.write(f'Name: {name} - Age: {age} - Best Game: {best_game}\n')
First of all, you need to know the difference between 'a' and 'w' in with open. 'w' stands for write, meaning every time you call it, it will be overwritten. 'a' stands for append, meaning new information will be appended to the file. In your case, I would have written the code something like this
userInput = input(“Enter your name: “)
with open(“filename.txt”, “a”) as f:
f.write(userInput)
If you instead want to overwrite every time - change the 'a' to a 'w'.

How to not duplicate elements when entering array in csv

I have a piece of code used to enter student information. But I want to transform it so that Admission no. cannot be repeated, when entering an existing number, a message will be printed if you want to re-enter an existing number. below is my code
import csv
student_fields = ['Admission no.','Name','Age','Email','Phone']
student_database = 'students.csv'
def add_student():
print("-------------------------")
print("Add Student Information")
print("-------------------------")
global student_fields
global student_database
student_data = []
for field in student_fields:
print(field)
value = input("Enter " + field + ": ")
student_data.append(value)
with open(student_database,"a",encoding = "utf-8") as f:
writer = csv.writer(f)
writer.writerows([student_data])
print("Data saved successfully")
input("Press any key to continue")
return
You can do something like this. As Barmar suggested, put the admission numbers in a set at the start of your definition. Then, check the user's input against those numbers. Create a while loop that doesn't let the user input any other value until they enter a new Admission no (and tell them that they are entering a duplicate admission number). Once everything looks good, write it to the csv.
import csv
student_fields = ['Admission no.','Name','Age','Email','Phone']
student_database = 'students.csv'
def add_student():
print("-------------------------")
print("Add Student Information")
print("-------------------------")
global student_fields
global student_database
# create a set of the already entered admission numbers
with open('students.csv', 'r') as file:
reader = csv.reader(file)
admissionNums = {x[0] for x in reader if x}
student_data = []
for field in student_fields:
print(field)
value = input("Enter " + field + ": ")
# while the user is entering the admission no. field and they are entering a duplicate, keep prompting them for a new/unique number
while field == 'Admission no.' and value in admissionNums:
print("Admission no. already in file, try again")
value = input("Enter " + field + ": ")
student_data.append(value)
# I also added `newline=''` so that it would stop creating an empty row when writing to the file
# You can remove this if you want to keep making a new row every time you write to it
with open(student_database,"a",encoding = "utf-8", newline='') as f:
writer = csv.writer(f)
writer.writerows([student_data])
print("Data saved successfully")
input("Press any key to continue")
# The return statement here is not necessary

How can I create an input that will loop and create a new list each time?

in case it isn't already obvious im new to python so if the answers could explain like im 5 years old that would be hugely appreirecated.
I'm basically trying to prove to myself that I can apply some of the basic that I have learnt into making a mini-contact book app. I don't want the data to save after the application has closed or anything like that. Just input your name, phone number and the city you live in. Once multiple names are inputted you can input a specific name to have their information printed back to you.
This is what I have so far:
Name = input("enter name here: ")
Number = input("enter phone number here: ")
City = input("enter city here: ")
User = list((Name, Number, City))
This, worked fine for the job of giving python the data. I made another input that made python print the information back to me just to make sure python was doing what I wanted it to:
print("Thank you! \nWould you like me to read your details back to you?")
bck = input("Y / N")
if bck == "Y":
print(User)
print("Thank you! Goodbye")
else:
print("Goodbye!")
The output of this, is the list that the user creates through the three inputs. Which is great! I'm happy that I have managed to make it function so far;
But I want the 'Name' input to be what names the 'User' list. This way, if I ask the user to input a name, that name will be used to find the list and print it.
How do I assign the input from Name to ALSO be what the currently named "User" list
You will need to create a variable which can store multiple contacts inside of it. Each contact will be a list (or a tuple. Here I have used a tuple, but it doesn't matter much either way).
For this you could use a list of lists, but a dictionary will be more suitable in this case.
What is a dictionary?
A dictionary is just like a list, except that you can give each of the elements a name. This name is called a "key", and it will most commonly be a string. This is perfect for this use case, as we want to be able to store the name of each contact.
Each value within the dictionary can be whatever you want - in this case, it will be storing a list/tuple containing information about a user.
To create a dictionary, you use curly brackets:
empty_dictionary = {}
dictionary_with_stuff_in_it = {
"key1": "value1",
"key2": "value2"
}
To get an item from a dictionary, you index it with square brackets, putting a key inside the square brackets:
print(dictionary_with_stuff_in_it["key1"]) # Prints "value1"
You can also set an item / add a new item to a dictionary like so:
empty_dictionary["a"] = 1
print(empty_dictionary["a"]) # Prints 1
How to use a dictionary here
At the start of the code, you should create an empty dictionary, then as input is received, you should add to the dictionary.
Here is the code I made, in which I have used a while loop to continue receiving input until the user wants to exit:
contacts = {}
msg = "Would you like to: \n - n: Enter a new contact \n - g: Get details for an existing contact \n - e: Exit \nPlease type n, g, or e: \n"
action = input(msg)
while action != "e":
if action == "n": # Enter a new contact
name = input("Enter name here: ")
number = input("Enter phone number here: ")
city = input("Enter city here: ")
contacts[name] = (number, city)
print("Contact saved! \n")
action = input(msg)
elif action == "g": # Get details for an existing contact
name = input("Enter name here: ")
try:
number, city = contacts[name] # Get that contact's information from the dictionary, and store it into the number and city variables
print("Number:", number)
print("City:", city)
print()
except KeyError: # If the contact does not exist, a KeyError will be raised
print("Could not find a contact with that name. \n")
action = input(msg)
else:
action = input("Oops, you did not enter a valid action. Please type n, g, or e: ")
#can be easier to use with a dictionary
#but its just basic
#main list storing all the contacts
Contact=[]
#takes length of contact list,'int' just change input from string to integer
contact_lenght=int(input('enter lenght for contact'))
print("enter contacts:-")
#using for loop to add contacts
for i in range(0,len(contact_lenght)):
#contact no.
print("contact",i+1)
Name=input('enter name:')
Number=input('enter number:')
City=input("enter city:")
#adding contact to contact list using .append(obj)
Contact.append((Name,Number,City))
#we can directly take input from user using input()
bck=input("Thank you! \nWould you like me to read your details back to you?[y/n]:")
#checking if user wants to read back
if bck=='y':
u=input("enter your name:")
#using for loop to read contacts
for i in range(0,len(Contact)):
#if user name is same as contact name then print contact details
if u==Contact[i][0]:
print("your number is",Contact[i][1])
print("your city is",Contact[i][2])
else:
#if user doesnt want to read back then print thank you
print("Good bye")
For this purpose you should use a dictionary.
The key of every entry should be the string 'User[0]' that corresponds to the person's name.
The contents of every entry should be the list with the information of that user.
I'll give you an example:
# first we need to create an empty dictionary
data = {}
# in your code when you want to store information into
# the dictionary you should do like this
user_name = User[0] # this is a string
data[user_name] = User # the list with the information
If you want to access the information of one person you should do like this:
# user_you_want string with user name you want the information
data[user_you_want]
Also you can remove information with this command:
del data[user_you_want_to_delete]
You can get more information on dictionaries here: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
You should start by defining a class to support name, phone and city. Once you've done that, everything else is easy.
class Data:
def __init__(self, name, city, phone):
self.name = name
self.city = city
self.phone = phone
def __eq__(self, other):
if isinstance(other, str):
return self.name == other
if isinstance(name, type(self)):
return self.name == other.name and self.city == other.city and self.phone == other.phone
return False
def __str__(self):
return f'Name={self.name}, City={self.city}, Phone={self.phone}'
DataList = []
while (name := input('Name (return to finish): ')):
city = input('City: ')
phone = input('Phone: ')
DataList.append(Data(name, city, phone))
while (name := input('Enter name to search (return to finish): ')):
try:
print(DataList[DataList.index(name)])
except ValueError:
print('Not found')

Python- Update txt file every time data appended to print

Currently I'm doing my first project which consists on a program for restaurants.
To log in as a waiter/tres you insert your name and is added to a TXT file.
My problem is that in the code when I print the TXT file to see the users that signed in it won't show the updated list if not the original list.
snames = list()
f_n = (open('names.txt')).read()
print("Welcome to NAME.app")
try:
while True:
name = input("Please select waiter/tress NAME - ADD to save new name - LIST to see saved names:")
if name.lower() == "add":
n_input = input("Name:")
with open('names.txt', 'a') as f:
f.write(n_input + '\n')
continue
elif name.lower() == "list":
print(f_n.split())
elif name == snames:
print("Logged as", name)#doubtful line. print name of list.
elif name == "exit":
exit()
except:
print("Invalid input")
In the second ELIF is what I wrote to see saved names(users).
But as I said prints the TXT file without including what I added in the first IF.
This might help.
OUTPUT
Welcome to NAME.app
Please select waiter/tress NAME - ADD to save new name - LIST to see saved names:add
Name:Python
Please select waiter/tress NAME - ADD to save new name - LIST to see saved names:list
['Ale', 'Sarah', 'Annette', 'Dan']
Please select waiter/tress NAME - ADD to save new name - LIST to see saved names:
Appreciate recommendations and solutions.
thank you very much.
In the first line you read all the names, only after that you added more names, so the f_n variable doesn't get updated.
Change the "list" option to this
elif name.lower() == "list":
with open('names.txt') as f:
print(f.read().splitlines())
This will make sure to read the updated list each time you choose this option

How to write to a text file using iteration?

My code does not write to a file, what am I doing wrong? I am trying to program to continue to ask for products until the user does not enter a product code. I want all products to be saved in the file.
store_file = open("Database.txt", "w")
NewProduct = ""
while NewProduct != False:
contine = input("Press 1 to enter a new product press 2 to leave: ")
if contine == "1":
print("Enter your product information")
information = []
product = input("What's the product code: ")
information.append(product)
description = input("Give a description of the product: ")
information.append(description)
price = input("Enter price of product: ")
information.append(price)
information = str(information)
clean = information.replace("]","").replace("[","").replace(",","").replace("'","")
store_file.write(clean)
elif contine == "2":
NewProduct = False
else:
print("Your input is invalid")
store_file.close
I got the program working with the following adjustments. See comments for explanations:
store_file = open("Database.txt", "w")
NewProduct = ""
while NewProduct != False:
continue = raw_input("Press 1 to enter a new product press 2 to leave: ")
#Changed to raw_input because input was reading in an integer for 1 rather than a
#string like you have set up. This could be specific to my IDE
if continue == "1":
print("Enter your product information")
information = []
product = raw_input("What's the product code: ")
information.append(product)
description = raw_input("Give a description of the product: ")
information.append(description)
price = raw_input("Enter price of product: ")
information.append(price)
information = str(information)
clean = information.replace("]","").replace("[","").replace(",","").replace("'","")
store_file.write(clean + "\n")
#Added a line break at the end of each file write
elif contine == "2":
NewProduct = False
else:
print("Your input is invalid")
store_file.close() #Added parentheses to call the close function
I'm assuming the problem here is that you're using Python 2, and input isn't doing what you think it does. In Python 2, input evals the input as if it were Python source code, so if someone enters 2, it's going to return the int value 2, not "2". In Python 2, you want to use raw_input, always (eval-ing random user input not being secure/reliable).
Also, while on CPython (the reference interpreter) files tend to naturally close themselves when they go out of scope, you made an effort to close, but forgot to actually call the close method; store_file.close looks up the method without calling it, store_file.close() would actually close it. Of course, explicit close is usually the wrong approach; you should use a with statement to avoid the possibility of forgetting to close (or of an exception skipping the close). You can replace:
store_file = open("Database.txt", "w")
...
store_file.close()
with:
with open("Database.txt", "w") as store_file:
... do all your work that writes to the file indented within the with block ...
... When you dedent from the with block, the file is guaranteed to be closed ...
There are other issues though. What you're doing with:
information = str(information)
information = information.replace("]","").replace("[","").replace(",","").replace("'","")
is terrible. I'm 99% sure what you really wanted was to just join the inputs with spaces. If you switch all your input calls to raw_input (only on Python 2, on Python 3, input is like raw_input on Python 2), then your list is a list of str, and you can just join them together instead of trying to stringify the list itself, then remove all the list-y bits. You can replace both lines above with just:
information = ' '.join(information)

Categories