How to: Read from a dictionary and append to it - python

What I want to do is, everytime a user makes a new entry, the dictionary should be doing a new entry into my list_1.txt and then read back from it.
I got the "adding content to list_1.txt" part but I don't know how I possibly could make my dictonary read back from it.
def dictionary():
dict1 = {"name": "xyz",
"age": 25,
"hobby": "Dancing"}
if input("Do you want to update the values?[y/n]: ") == "y":
dict1["name"] = str(input("Change the name to: "))
print(dict1["name"])
dict1["age"] = int(input("Change the age to: "))
print(dict1["age"])
dict1["hobby"] = str(input("Change the hobby to: "))
print(dict1["hobby"])
elif input() != "y":
print("No valid input");
elif input() == "n":
print("Here is the current Data: " + str(dict1))
sys.exit()
print(dict1)
appendFile = open('list_1.txt','a')
appendFile.write("\n" + str(dict1))
appendFile.close()
This is the current state of the code. I already tried creating "readMe = open("list_1.txt","r").read()" and calling it inside "dict1" but as you can imagine it went horribly wrong. I'd be grateful for anykind of help and advice you could contribute.
P.S: I know my menu is buggy but I didn't put any time into it yet. This is just a little project to learn python.

It's easy to do so with the JSON module, which stores Python objects into a storage format called JSON.
Add a check in the beginning of your function to see if the file exists. If it doesn't use your default values for the dictionary, otherwise load the data from the file.
def dictionary():
if os.path.exists('list_1.txt'): # load dictionary if exists
with open('list_1.txt', 'r') as f:
dict1 = json.load(f)
else:
dict1 = { # otherwise use default values
"name": "xyz",
"age": 25,
"hobby": "Dancing"
}
When the program is done, output the data to a text file:
with open('list_1.txt', 'w') as f:
json.dump(dict1, f)
Final program:
import os
import sys
import json
def dictionary():
if os.path.exists('list_1.txt'): # load dictionary if exists
with open('list_1.txt', 'r') as f:
dict1 = json.load(f)
else:
dict1 = { # otherwise use default values
"name": "xyz",
"age": 25,
"hobby": "Dancing"
}
if input("Do you want to update the values?[y/n]: ") == "y":
dict1["name"] = str(input("Change the name to: "))
print(dict1["name"])
dict1["age"] = int(input("Change the age to: "))
print(dict1["age"])
dict1["hobby"] = str(input("Change the hobby to: "))
print(dict1["hobby"])
elif input() != "y":
print("No valid input");
elif input() == "n":
print("Here is the current Data: " + str(dict1))
sys.exit()
print(dict1)
with open('list_1.txt', 'w') as f: # save dict
json.dump(dict1, f)

use json module in python
import json
#assming folling is content of your text file
# {
# "name": "xyz",
# "age": 25,
# "hobby": "Dancing"
# }
#context manager // auto close file outside "with" clause
with open("list_1.txt",'r') as file:
#convert string '{"name": "xyz","age": 25, "hobby": "Dancing" }' into
#dictionary dict1
dict1=json.loads( file.read() )
if input("Do you want to update the values?[y/n]: ") == "y":
dict1["name"] = str(input("Change the name to: "))
print(dict1["name"])
dict1["age"] = int(input("Change the age to: "))
print(dict1["age"])
dict1["hobby"] = str(input("Change the hobby to: "))
print(dict1["hobby"])
elif input() != "y":
print("No valid input");
elif input() == "n":
print("Here is the current Data: " + str(dict1))
sys.exit()
print(dict1)
# appendFile = open('list_1.txt','a')
# appendFile.write("\n" + str(dict1))
# appendFile.close()
#use this instead
with open('list_1.txt','w') as file:
#convert dict to string
content = json.dumps(dict1)
file.write(content)
you can also use numpy
np.save('list_1.npy', dictionary)
#file extension must me .npy

Related

How to delete given element from a python dictionary?

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?

Changing the string value that uses return file.name after creating name file

I'm really new to Python. Only one week of study so please I know this is not the best possible way of doing things but I'm trying. So I have this memo "muistio.txt"and after program checks if it already exists or not you can make some simple inputs.
Everything works okay but after Choice 4 I want to change part print("You're at currently",name) for the file name that was created and using it until new one is created or program is closed.
How do I achieve this?
import time
def finding_file():
try:
file = open("muistio.txt", "r")
return file.name
except IOError:
file = open("note.txt", "w")
print("Can't find the file, creating.")
filename = file.name
return filename
def new_memo():
memo = input("Give name: ")
try:
memo = open(memo, "r")
print("Using memo: " + memo.name)
memoname = memo.name
return memoname
except IOError:
memo = open(memo, "w")
print("Memo not found, creating")
memoname = memo.name
return memoname
def main():
while True:
name = finding_file(),new_memo()
print("You're at currently", name)
print("(1) Read\n(2) Add\n(3) Empty\n(4)Change\n(5) Quit")
choice = int(input("What you want to do?: "))
if choice == 1:
memo = open("muistio.txt", "r")
inside = memo.read()
print(inside)
memo.close()
elif choice == 2:
memo = open("muistio.txt", "a")
writing = input("Write new note: ")
timestamp = time.strftime("%X %x")
memo.write(writing+":::"+timestamp)
memo.close()
elif choice == 3:
memo = open("muistio.txt", "w")
memo.truncate(0)
print("Memo empty.")
memo.close()
elif choice == 4:
new_memo()
elif choice == 5:
print("Quitting.")
break
if __name__ == "__main__":
main()

How do I create a dictionary from a file using Python?

Question: How do I open a file and turn it into my dictionary when I run the program?
So I created a test dictionary, saved it as .txt and .dat. Below I have entered the dictionary manually, but instead I want the program to open the file when ran, convert it to the dictionary, then continue into the functions.
(The overall objective of the program is to enter a key (productCode) to retrieve the product number, all of which works), but I want it to do it with the file, and not the manually entered data.
As always, guidance is appreciated!
file = open("test.dat", "r")
FILENAME = "test.dat"
# ------ Global Variables -------
d = {'ABCD': '0123', 'HJKL': '0987'}
user_cont = True
# ------- Functions -------
print("Product number finder.")
def get_productNum2():
global d
user_cont = True
while user_cont:
productCode = input("Enter an existing product code: ")
if productCode in d:
productNum = d[productCode]
print("Product #: " + productNum)
else:
print("Error finding product number; product code does not exist.")
user_cont = user_continue()
def user_continue():
global user_cont
prompt_user = input("Do you wish to continue? Enter y/n: ")
if prompt_user == "y":
user_cont = True
elif prompt_user == "n":
user_cont = False
return user_cont
# ------- Start Execution -------
get_productNum2()
You can (and should) write a dictionary to file in JSON format. Not only is it saved in a human-readable way, the JSON format also means the dictionary can even be loaded into many other programming languages and programs if needed!
Here is an example using the standard library package json:
import json
dict = {'ABCD': '0123', 'HJKL': '0987'}
dict_json = json.dumps(dict) #this line turns the dictionary into a JSON string
with open("my_dictionary.json", "w") as outfile:
outfile.write(dict_json)
Given a dictionary in JSON format, we can load it like this:
with open("my_dictionary.json", "r") as infile:
dict = json.load(infile)
Now you can access dict which you loaded from file as if it were the original dictionary:
>>> print(dict["ABCD"])
0123

Python, Writing the file twice

I'm trying to get my code so it will update Y7,Set1.txt but it keeps writing the data inside it again, + my new data that was added.
My code below:
print("Registration System")
print("Make sure their is atleast one name in register!")
password = ("admin")
check = input("The Administration Password is: ")
if check == password:
input("Enter any key to continue ")
print("If their is no names in the register.txt\nThe script will stop working here!")
set1 = list()
set2 = list()
set3 = list()
set4 = list()
set5 = list()
with open("register.txt", "r") as register:
registers = [line.rstrip("\n") for line in register]
for pop in registers:
print(pop)
choice = input(
'Where would you like it to go? (Enter 1 - set1, enter 2 - set2)')
if choice == '1':
set1.append(pop)
elif choice == '2':
set2.append(pop)
elif choice == '3':
set3.append(pop)
elif choice == '4':
set4.append(pop)
elif choice == '5':
set5.append(pop)
with open("Y7,Set2.txt", "r") as Y7R:
Y7 = [line.rstrip("\n") for line in Y7R]
with open("Y7,Set2.txt", "w") as Y7Y:
data = (str(Y7) + str(set2))
Y7Y.writelines(data)
with open("Y7,Set1.txt", "r") as d:
Y7S = [line.rstrip("\n") for line in d]
with open("Y7,Set1.txt", "w") as Y7D:
data2 = str(Y7S) + str(set1)
Y7D.writelines(data2)
else:
print("Access Denied!")
However the text file keeps printing the previous values, + a lot of ///////
Anyway I can get my code just to add information to that file, without adding all the /// and previous names? Thanks!
What's happening in the file is:
['[\'[\\\'[\\\\\\\'[\\\\\\\\\\\\\\\'[\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'[\\\\\\\
PaulBrennan\\\\\\\\\
Open the file with "a" mode. "r" mode is used when the file only needs to be read and "w" for only writing (an existing file with the same name will be erased).
open("Y7,Set2.txt", "a")
You can check the docs.

python: Adding to username

I am fairly new to python and I need to make a program to ask 10 questions, save the score into a file and allow someone to read the scores in from the file.
My problem: I need to check if the person who has done the quiz already has a record in the file, and if so, I need to add their score to the end of their record.
The records should look like this:
name,score,score,score,score,
etc so they can be split using commas.
I am also looking for the simplest answer, not the most efficient. Also, if you could comment the code, it would make it much easier. Here is my code so far:
import random
import math
import operator as op
import sys
import re
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, num1)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correct_result = operation(num1, num2)
print ("What is {} {} {}?".format(num1, rand_key, num2))
while True:
try:
user_answer = int(input("Your answer: "))
except ValueError:
print("Only enter numbers!")
continue
else:
break
if user_answer != correct_result:
print ("Incorrect. The right answer is {}".format(correct_result))
return False
else:
print("Correct!")
return True
print("1. Are you a student?")
print("2. Are you a teacher?")
print("3. Exit")
while True:
try:
status = int(input("Please select an option:"))
except ValueError:
print("Please enter a number!")
else:
if status not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
break
if status == 1:
username=input("What is your name?")
while not re.match("^[A-Za-z ]*$", username) or username=="":
username=input(str("Please enter a valid name (it must not contain numbers or symbols)."))
print ("Hi {}! Wellcome to the Arithmetic quiz...".format(username))
while True:
try:
users_class = int(input("Which class are you in? (1,2 or 3)"))
except ValueError:
print("Please enter a number!")
else:
if users_class not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
break
correct_answers = 0
num_questions = 10
for i in range(num_questions):
if test():
correct_answers +=1
print("{}: You got {}/{} {} correct.".format(username, correct_answers, num_questions,
'question' if (correct_answers==1) else 'questions'))
if users_class == 1:
class1 = open("Class1.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class1.write(newRecord)
class1.close()
elif users_class == 2:
class2 = open("Class2.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class2.write(newRecord)
class2.close()
elif users_class == 3:
class3 = open("Class3.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class3.write(newRecord)
class3.close()
else:
print("Sorry, we can not save your data as the class you entered is not valid.")
EDIT:
Add this function before your "test" function:
def writeUserScore(file, name, score):
with open (file, "r") as myfile:
s = myfile.read()
rows = s.split("\n")
data = {}
for row in rows:
tmp = row.split(",")
if len(tmp) >= 2: data[tmp[0]] = tmp[1:]
if name not in data:
data[name] = []
data[name].append(str(score))
output = ""
for name in data:
output = output + name + "," + ",".join(data[name]) + "\n"
handle = open(file, "w+")
handle.write(output)
handle.close()
After that, where you have "if users_class == 1:" do this:
writeUserScore("Class1.txt", username, str(correct_answers))
Do the same for the other two else ifs.
Let me know what you think!
Try using a dictionary to hold the existing file data.
Read the file in a variable called "str" for example. And then do something like this:
rows = str.split("\n")
data1 = {}
for row in rows:
tmp = row.split(",")
data1[tmp[0]] = tmp[1:]
When you have a new score you should then do:
if username not in data1:
data1[username] = []
data1[username] = str(correct_answers)
And to save the data back to the file:
output = ""
for name in data1:
output = outupt + name + "," + ",".join(data1[name]) | "\n"
And save the contents of "output" to the file.
PS: If you are not bound by the file format you can use a JSON file. I can tell you more about this if you wish.
Hope that helps,
Alex
First, define these functions:
from collections import defaultdict
def read_scores(users_class):
"""
If the score file for users_class does not exist, return an empty
defaultdict(list). If the score file does exist, read it in and return
it as a defaultdict(list). The keys of the dict are the user names,
and the values are lists of ints (the scores for each user)
"""
assert 0 <= users_class <= 3
result = defaultdict(list)
try:
lines =open("Class%d.txt"%users_class,'r').readlines()
except IOError:
return result
for line in lines:
# this line requires python3
user, *scores = line.strip().split(',')
# if you need to use python2, replace the above line
# with these two lines:
# line = line.strip().split(',')
# user, scores = line[0], line[1:]
result[user] = [int(s) for s in scores]
return result
def write_scores(users_class, all_scores):
"""
Write user scores to the appropriate file.
users_class is the class number, all scores is a dict kind of dict
returned by read_scores.
"""
f = open("Class%d.txt"%users_class,'w')
for user, scores in all_scores.items():
f.write("%s,%s\n"%(user, ','.join([str(s) for s in scores])))
def update_user_score(users_class, user_name, new_score):
"""
Update the appropriate score file for users_class.
Append new_score to user_name's existing scores. If the user has
no scores, a new record is created for them.
"""
scores = read_scores(users_class)
scores[user_name].append(new_score)
write_scores(users_class, scores)
Now, in the last portion of your code (where you actually write the scores out) becomes much simpler. Here's an example of writing some scores:
update_user_score(1, 'phil', 7)
update_user_score(1, 'phil', 6)
update_user_score(1, 'alice', 6)
update_user_score(1, 'phil', 9)
there will be two lines in Class1.txt:
phil,7,6,9
alice,6
We read the whole file into a dict (actually a defaultdict(list)),
and overwrite that same file with an updated dict. By using defaultdict(list), we don't have to worry about distinguishing between updating and adding a record.
Note also that we don't need separate if/elif cases to read/write the files. "Scores%d.txt"%users_class gives us the name of the file.

Categories