i've written a tool in python where you enter a title, content, then tags, and the entry is then saved in a pickle file. it was mainly designed for copy-paste functionality (you spot a piece of code you like on the net, copy it, and paste it into the program), not really for handwritten content, though it does that with no problem.
i mainly did it because i'm always scanning through my pdf files, books, or the net for some coding example of solution that i'd already seen before, and it just seemed logical to have something where you could just put the content in, give it a title and tags, and just look it up whenever you needed to.
i realize there are sites online that handle this ex. http://snippets.dzone.com, but i'm not always online when i code. i also admit that i didn't really look to see if anyone had written a desktop app, the project seemed like a fun thing to do so here i am.
it wasn't designed with millions of entries in mind, so i just use a pickle file to serialize the data instead of one of the database APIs. the query is also very basic, only title and tags and no ranking based on the query.
there is an issue that i can't figure out, when you are at the list of entries there's a try, except clause where it tries to catch a valid index (integer). if you enter an inavlid integer, it will ask you to enter a valid one, but it doesn't seem to be able to assign it to the variable. if you enter a valid integer straightaway, there are no problems and the entry will display.
anyway let me know what you guys think. this is coded for python3.
main file:
#!usr/bin/python
from archive_functions import Entry, choices, print_choice, entry_query
import os
def main():
choice = ''
while choice != "5":
os.system('clear')
print("Mo's Archive, please select an option")
print('====================')
print('1. Enter an entry')
print('2. Lookup an entry')
print('3. Display all entries')
print('4. Delete an entry')
print('5. Quit')
print('====================')
choice = input(':')
if choice == "1":
entry = Entry()
entry.get_data()
entry.save_data()
elif choice == "2":
queryset = input('Enter title or tag query: ')
result = entry_query('entry.pickle', queryset)
if result:
print_choice(result, choices(result))
else:
os.system('clear')
print('No Match! Please try another query')
pause = input('\npress [Enter] to continue...')
elif choice == "3":
queryset = 'all'
result = entry_query('entry.pickle', queryset)
if result:
print_choice(result, choices(result))
elif choice == "4":
queryset = input('Enter title or tag query: ')
result = entry_query('entry.pickle', queryset)
if result:
entry = result[choices(result)]
entry.del_data()
else:
os.system('clear')
print('No Match! Please try another query')
pause = input('\npress [Enter] to continue...')
elif choice == "5":
break
else:
input('please enter a valid choice...')
main()
if __name__ == "__main__":
main()
archive_functions.py:
#!/bin/usr/python
import sys
import pickle
import os
import re
class Entry():
def get_data(self):
self.title = input('enter a title: ')
print('enter the code, press ctrl-d to end: ')
self.code = sys.stdin.readlines()
self.tags = input('enter tags: ')
def save_data(self):
with open('entry.pickle', 'ab') as f:
pickle.dump(self, f)
def del_data(self):
with open('entry.pickle', 'rb') as f:
data_list = []
while True:
try:
entry = pickle.load(f)
if self.title == entry.title:
continue
data_list.append(entry)
except:
break
with open('entry.pickle', 'wb') as f:
pass
with open('entry.pickle', 'ab') as f:
for data in data_list:
data.save_data()
def entry_query(file, queryset):
'''returns a list of objects matching the query'''
result = []
try:
with open(file, 'rb') as f:
entry = pickle.load(f)
os.system('clear')
if queryset == "all":
while True:
try:
result.append(entry)
entry = pickle.load(f)
except:
return result
break
while True:
try:
if re.search(queryset, entry.title) or re.search(queryset, entry.tags):
result.append(entry)
entry = pickle.load(f)
else:
entry = pickle.load(f)
except:
return result
break
except:
print('no entries in file, please enter an entry first')
pause = input('\nPress [Enter] to continue...')
def choices(list_result):
'''takes a list of objects and returns the index of the selected object'''
os.system('clear')
index = 0
for entry in list_result:
print('{}. {}'.format(index, entry.title))
index += 1
try:
choice = int(input('\nEnter choice: '))
return choice
except:
pause = input('\nplease enter a valid choice')
choices(list_result)
def print_choice(list_result, choice):
'''takes a list of objects and an index and displays the index of the list'''
os.system('clear')
print('===================')
print(list_result[choice].title)
print('===================')
for line in list_result[choice].code:
print(line, end="")
print('\n\n')
back_to_choices(list_result)
def back_to_choices(list_result):
print('1. Back to entry list')
print('2. Back to Main Menu')
choice = input(':')
if choice == "1":
print_choice(list_result, choices(list_result))
elif choice == "2":
pass
else:
print('\nplease enter a valid choice')
back_to_choices(list_result)
In the else, you call the main function again recursively. Instead, I'd do something like choice == "0", which will just cause the while loop to request another entry. This avoids a pointless recursion.
Related
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()
I have created a program where I have two text files: "places.txt" and "verbs.txt" and It asks the user to choose between these two files. After they've chosen it quizzes the user on the English translation from the Spanish word and returns the correct answer once the user has completed their "test". However the program runs smoothly if the text files are free in the folder for python I have created on my Mac but once I put these files and the .py file in a subfolder it says files can't be found. I want to share this .py file along with the text files but would there be a way I can fix this error?
def CreateQuiz(i):
# here i'm creating the keys and values of the "flashcards"
f = open(fileList[i],'r') # using the read function for both files
EngSpanVocab= {} # this converts the lists in the text files to dictionaries
for line in f:
#here this trims the empty lines in the text files
line = line.strip().split(':')
engWord = line[0]
spanWord = line[1].split(',')
EngSpanVocab[engWord] = spanWord
placeList = list(EngSpanVocab.keys())
while True:
num = input('How many words in your quiz? ==>')
try:
num = int(num)
if num <= 0 or num >= 10:
print('Number must be greater than zero and less than or equal to 10')
else:
correct = 0
#this takes the user input
for j in range(num):
val = random.choice(placeList)
spa = input('Enter a valid spanish phrase for '+val+'\n'+'==> ')
if spa in EngSpanVocab[val]:
correct = correct+1
if len(EngSpanVocab[val]) == 1:
#if answers are correct the program returns value
print('Correct. Good work\n')
else:
data = EngSpanVocab[val].copy()
data.remove(spa)
print('Correct. You could also have chosen',*data,'\n')
else:
print('Incorrect, right answer was',*EngSpanVocab[val])
#gives back the user answer as a percentage right out of a 100%
prob = round((correct/num)*100,2)
print('\nYou got '+str(correct)+' out of '+str(num)+', which is '+str(prob)+'%'+'\n')
break
except:
print('You must enter an integer')
def write(wrongDict, targetFile):
# Open
writeFile = open(targetFile, 'w')
# Write entry
for key in wrongDict.keys():
## Key
writeFile.write(key)
writeFile.write(':')
## Value(s)
for value in wrongDict[key]:
# If key has multiple values or user chooses more than 1 word to be quizzed on
if value == wrongDict[key][(len(wrongDict[key])) - 1]:
writeFile.write(value)
else:
writeFile.write('%s,'%value)
writeFile.write('\n')
# Close
writeFile.close()
print ('Incorrect answers written to',targetFile,'.')
def writewrong(wringDict):
#this is for the file that will be written in
string_1= input("Filename (defaults to \'wrong.txt\'):")
if string_1== ' ':
target_file='wrong.txt'
else:
target_file= string_1
# this checs if it already exists and if it does then it overwrites what was on it previously
if os.path.isfile(target)==True:
while True:
string_2=input("File already exists. Overwrite? (Yes or No):")
if string_2== ' ':
write(wrongDict, target_file)
break
else:
over_list=[]
for i in string_1:
if i.isalpha(): ovrList.append(i)
ovr = ''.join(ovrList)
ovr = ovr.lower()
if ovr.isalpha() == True:
#### Evaluate answer
if ovr[0] == 'y':
write(wrongDict, target)
break
elif ovr[0] == 'n':
break
else:
print ('Invalid input.\n')
### If not, create
else:
write(wrongDict, target)
def MainMenu():
## # this is just the standad menu when you first run the program
if len(fileList) == 0:
print('Error! No file found')
else:
print( "Vocabulary Program:\nChoose a file with the proper number or press Q to quit" )
print(str(1) ,"Places.txt")
print(str(2) ,"Verbs.txt")
while True:
#this takes the user input given and opens up the right text file depending on what the user wants
MainMenu()
userChoice = input('==> ')
if userChoice == '1':
data = open("places.txt",'r')
CreateQuiz(0)
elif userChoice == '2':
data = open("verbs.txt",'r')
CreateQuiz(1)
elif userChoice == 'Q':
break
else:
print('Choose a Valid Option!!\n')
break
You are probably not running the script from within the new folder, so it tries to load the files from the directory from where you run the script.
Try setting the directory:
import os
directory = os.path.dirname(os.path.abspath(__file__))
data = open(directory + "/places.txt",'r')
So I'm doing a ToDo app, and I need to save an array of sentences and words to a .txt file. I have done some research but haven't found any tutorials that explain it well enough so I could understand it. As I said I'm using Python 3. Code below:
# Command line TO-DO list
userInput = None
userInput2 = None
userInput3 = None
todo = []
programIsRunning = True
print("Welcome to the TODO list made by Alex Chadwick. Have in mind
that closing the program will result in your TODO"
" list to DISAPPEAR. We are working on correcting that.")
print("Available commands: add (will add item to your list); remove
(will remove item from your list); viewTODO (will"
" show you your TODO list); close (will close the app")
with open('TODOList.txt', 'r+') as f:
while programIsRunning == True:
print("Type in your command: ")
userInput = input("")
if userInput == "add":
print("Enter your item")
userInput2 = input("")
todo.append(userInput2)
continue
elif userInput == "viewTODO":
print(todo)
continue
elif userInput == "remove":
print(todo)
userInput3 = input("")
userInput3 = int(userInput3)
userInput3 -= 1
del todo[userInput3]
continue
elif userInput == "close":
print("Closing TODO list")
programIsRunning = False
continue
else:
print("That is not a valid command")
This sounds like a job for pickle!
Pickle is a built-in module for saving objects and data in Python. To use it, you will need to put import pickle at the top of your program.
To save to a file:
file_Name = "testfile.save" #can be whatever you want
# open the file for writing
fileObject = open(file_Name,'wb')
# this writes the object to the file
pickle.dump(THING_TO_SAVE,fileObject)
# here we close the fileObject
fileObject.close()
To load from a file:
# we open the file for reading
fileObject = open(file_Name,'r')
# load the object from the file
LOADED_THING= pickle.load(fileObject)
fileObject.close()
The code in this answer was taken from here.
I hope that helps!
You use a simple text file to store your TODO - items and retrieve them from it:
import sys
fn = "todo.txt"
def fileExists():
"""https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-fi
answer: https://stackoverflow.com/a/82852/7505395
"""
import os
return os.path.isfile(fn)
def saveFile(todos):
"""Saves your file to disk. One line per todo"""
with open(fn,"w") as f: # will overwrite existent file
for t in todos:
f.write(t)
f.write("\n")
def loadFile():
"""Loads file from disk. yields each line."""
if not fileExists():
raise StopIteration
with open(fn,"r") as f:
for t in f.readlines():
yield t.strip()
def printTodos(todos):
"""Prints todos with numbers before them (1-based)"""
for i,t in enumerate(todos):
print(i + 1, t)
def addTodo(todos):
"""Adds a todo to your list"""
todos.append(input("New todo:"))
return todos
def deleteTodos(todos):
"""Prints the todos, allows removal by todo-number (as printed)."""
printTodos(todos)
i = input("Which number to delete?")
if i.isdigit() and 0 < int(i) <= len(todos): # 1 based
r = todos.pop(int(i) - 1)
print("Deleted: ", r)
else:
print("Invalid input")
return todos
def quit():
i = input("Quitting without saving [Yes] ?").lower()
if i == "yes":
exit(0) # this exits the while True: from menu()
def menu():
"""Main loop for program. Prints menu and calls subroutines based on user input."""
# sets up all available commands and the functions they call, used
# for printing commands and deciding what to do
commands = {"quit": quit, "save" : saveFile, "load" : loadFile,
"print" : printTodos,
"add": addTodo, "delete" : deleteTodos}
# holds the loaded/added todos
todos = []
inp = ""
while True:
print("Commands:", ', '.join(commands))
inp = input().lower().strip()
if inp not in commands:
print("Invalid command.")
continue
# some commands need params or return smth, they are handled below
if inp == "load":
try:
todos = [x for x in commands[inp]() if x] # create list, no ""
except StopIteration:
# file does not exist...
todos = []
elif inp in [ "save","print"]:
if todos:
commands[inp](todos) # call function and pass todos to it
else:
print("No todos to",inp) # print noting to do message
elif inp in ["add", "delete"]:
todos = commands[inp](todos) # functions with return values get
# todos passed and result overwrites
# it
else: # quit and print are handled here
commands[inp]()
def main():
menu()
if __name__ == "__main__":
sys.exit(int(main() or 0))
I want to be able to have a program whereby the user can input a paragraph/sentence/word/character whatever and have that stored in a list e.g. in list[0]. Then I want them to be able to write another bit of text and have that stored in e.g. list[1]. Then at any time I want the user to be able to read that from the list by choosing which segment they want to read from e.g. reading "hello" from list[0] whilst in list[1] "hi" is stored. Then when the user exits the program I want the list to be written to an external file. Then, at next start up, the program should read the file contents and store it again in the list so that the user can add more bits of text or read the current bits. When the list is saved to a file it should append new or changed parts but overwrite parts that are the same so as not to have duplicates. I have attempted this without much success. I am to be honest not sure if it is possible. I have browsed similar forums and have found that hasn't helped much so here it is.
My code so far:
import os
import time
import csv
global write_list
global f1_contents
write_list = []
def write():
os.system("cls")
user_story = input("Enter your text: \n")
write_list.append(user_story)
def read():
os.system("cls")
user_select_needs = True
while user_select_needs == True:
user_select = input("Enter the list section to read from or type exit: \n")
if user_select == "exit":
user_select_needs = False
try:
int(user_select)
select = user_select
select = int(select)
try:
print(write_list[select])
user_select_needs = False
enter = input("Press enter:")
except:
print("There is not stored data on that section!")
except ValueError:
print("That is not a valid section!")
def exit():
os.system("cls")
max_num_needs = True
while max_num_needs == True:
set_max_num = input("Set the storage: \n")
try:
int(set_max_num)
max_num = set_max_num
max_num = int(max_num)
max_num_needs = False
except:
print("It must be an integer!")
for i in range(0, max_num):
f = open("Saves.txt", "a")
f.write(write_list[i])
f.close()
os._exit(1)
def main():
store_num_needs = True
while store_num_needs == True:
set_store_num = input("State the current storage amount: \n")
try:
int(set_store_num)
store_num = set_store_num
store_num = int(store_num)
store_num_needs = False
except:
print("It must be an integer!")
try:
f1 = open("Saves.txt", "r")
for i in range(0, store_num+1):
i, = f1.split("#")
f1.close()
except:
print("--------Loading-------")
time.sleep(1)
while True:
os.system("cls")
user_choice = ""
print("Main Menu" + "\n" + "---------")
print("1) Write")
print("2) Read")
print("3) Exit")
while user_choice not in ["1", "2", "3"]:
user_choice = input("Pick 1, 2 or 3 \n")
if user_choice == "1":
write()
elif user_choice == "2":
read()
else:
exit()
if __name__ == "__main__":
main()
It might be too complicated to understand in which case just ask me in comments- otherwise general tips would be nice aswell.
Thanks in advance
A quick point of correction:
global is only required if you're defining a global variable inside a non-global context. In other words, anything defined at the default indentation level, will be accessible by everything else defined below it. For example:
def set_global():
x = 1
def use_global():
x += 1
set_global()
try:
use_global()
except Exception as e:
# `use_global` doesn't know
# about what `set_global` did
print("ERROR: " + str(e))
# to resolve this we can set `x` to a
# default value in a global context:
x = 1
# or, if it were required, we
# could create a global variable
def make_global():
global x
make_global()
# either will work fine
set_global()
use_global()
print(x) # prints 2
Now to the actual question:
I haven't read through the block of code you wrote (probably best to trim it down to just the relevant bits in the future), but this should solve the problem as I understand it, and you described it.
import os
import sys
user_text = []
# login the user somehow
user_file = 'saves.txt'
def writelines(f, lines):
"""Write lines to file with new line characters"""
f.writelines('\n'.join(lines))
def readlines(f):
"""Get lines from file split on new line characters"""
text = f.read()
return text.split('\n') if text else []
class _Choice(object):
"""Class that is equivalent to a set of choices
Example:
>>> class YesObj(Choice):
>>> options = ('y', 'yes')
>>> Yes = YesObj()
>>> assert Yes == 'yes'
>>> assert Yes == 'y'
>>> # assertions evaluate to True
Override the `options` attribute to make use
"""
allowed = ()
def __eq__(self, other):
try:
s = str(other)
except:
raise TypeError("Cannot compare with non-string")
else:
return s.lower() in self.allowed
def _choice_repr(choices):
allowed = []
for c in choices:
if isinstance(c, _Choice):
allowed.extend(c.allowed)
else:
allowed.append(c)
if len(allowed) > 2:
s = ', '.join([repr(c) for c in allowed[:-1]])
s += ', or %s' % repr(allowed[-1])
elif len(allowed) == 1:
s = '%s or %s' % allowed
else:
s = '%s' % allowed[0]
return s
def _choice_sentinel(name, allowed):
"""Creates a sentinel for comparing options"""
return type(name, (_Choice,), {'allowed': list(allowed)})()
Quit = _choice_sentinel('Quit', ('q', 'quit'))
Yes = _choice_sentinel('Yes', ('y', 'yes'))
No = _choice_sentinel('No', ('n', 'no'))
def readline_generator(f):
"""Generate a file's lines one at a time"""
t = f.readline()
# while the line isn't empty
while bool(t):
yield t
t = f.readline()
def read_from_cache():
"""Overwrite `user_text` with file content"""
if not os.path.isfile(user_file):
open(user_file, 'w').close()
globals()['user_text'] = []
else:
with open(user_file, 'r') as f:
lines = readlines(f)
# replace vs extend user text
for i, t in enumerate(lines):
if i == len(user_text):
user_text.extend(lines[i:])
else:
user_text[i] = t
def write_to_cache():
"""Overwrite cache after the first line disagrees with current text
If modifications have been made near the end of the file, this will
be more efficient than a blindly overwriting the cache."""
with open(user_file, 'r+') as f:
i = -1
last_pos = f.tell()
# enumerate is a generator, not complete list
for i, t in enumerate(readline_generator(f)):
if user_text[i] != t:
# rewind to the line before
# this diff was encountered
f.seek(last_pos)
# set the index back one in
# order to catch the change
i -= 1
break
last_pos = f.tell()
# then cut off remainder of file
f.truncate()
# recall that i is the index of the diff
# replace the rest of it with new
# (and potentially old) content
writelines(f, user_text[i+1:])
def blind_write_to_cache():
"""Blindly overwrite the cache with current text"""
with open(user_file, 'w') as f:
writelines(f, user_text)
def overwrite_user_text(i, text, save=False):
"""Overwrite a line of text
If `save` is True, then these changes are cached
"""
try:
user_text[i] = text
except IndexError:
raise IndexError("No text exists on line %r" % (i+1))
if save:
write_to_cache()
def user_input():
"""Get a new line from the user"""
return raw_input("input text: ")
def user_choice(msg, choices):
if len(choices) == 0:
raise ValueError("No choices were given")
ans = raw_input(msg)
if ans not in choices:
print("Invalid Response: '%s'" % ans)
m = "Respond with %s: " % _choice_repr(choices)
return user_choice(m, choices)
else:
return ans
def user_appends():
"""User adds a new line"""
user_text.append(user_input())
def user_reads(*args, **kwargs):
"""Print a set of lines for the user
Selects text via `user_text[slice(*args)]`
Use 'print_init' in kwargs to choose how
many lines are printed out before user must
scroll by pressing enter, or quit with 'q'."""
print_init = kwargs.get('print_init', 4)
sliced = user_text[slice(*args)]
if not isinstance(sliced, list):
sliced = [sliced]
for i, l in enumerate(sliced):
if i < print_init:
print(l)
sys.stdout.flush()
elif user_choice(l, ['', Quit]) == Quit:
break
def user_changes(i=None, save=False):
"""User changes a preexisting line"""
attempt = True
while i is None and attempt:
# get the line the user wants to change
i_text = raw_input("Line to be changed: ")
try:
# make user input an index
i = int(i_text)
except:
# check if they want to try again
c = user_choice("Bad input - '%s' is not an "
"integer. Try again? " % i_text, (Yes, No))
attempt = (c == Yes)
if attempt:
# user gave a valid integer for indexing
try:
user_reads(i-1)
overwrite_user_text(i-1, user_input(), save)
except Exception as e:
print("ERROR: %s" % e)
if user_choice("Try again? ", (Yes, No)):
user_changes(i, save)
# stores whatever text is already on
# file to `user_text` before use
read_from_cache()
I AM NEW TO PYTHON AND CODING IN GENERAL.
So I have a program with a menu that has multiple functions in it. individually each function works fine on its own, however when i put them together they would usually not fully execute and instead stop half way or wont work at all.
EXAMPLE- the function remove wont remove what i tell it to.
def show_coffee will only show the first description and weight only and nothing else.
What can i do to make the functions fully execute?
import os
def main():
choice =''
fun=[]
while choice != 4:
menu()
choice=getUserChoice()
if choice !=4:
fun=process_choice(choice,fun)
print(fun)
print("Goodby!")
def process_choice(choice,fun):
#fun=fun1
if choice == 0:
fun=add_coffee(fun)
elif choice == 1:
fun=show_coffee(fun)
elif choice == 2:
fun=search_coffee(fun)
elif choice == 3:
fun=modify_coffee(fun)
else:
print(choice,"is not a valid choice.")
return fun
def add_coffee(fun):
another= 'y'
coffee_file=open('coffee.txt', 'a')
Description={}
while another == 'y' or another == 'Y':
print('Enter the following coffee data:')
descr=input('Description: ')
qty= int(input('Quantity (in pounds): '))
coffee_file.write(descr + '\n')
coffee_file.write(str(qty) + '\n')
print("Do you want to add another record?")
another = input("Y=yes, anything else =no: ")
return fun
coffee_file.close()
print('Data append to coffee.txt.')
def show_coffee(fun2):
coffee_file=open ('coffee.txt', 'r')
descr=coffee_file.readline()
while descr != "":
qty= str(coffee_file.readline())
descr=descr.rstrip('\n')
print('Description:', descr)
print('Quantity:', qty)
descr= coffee_file.readline()
fun=fun2
return fun
coffee_file.close()
def search_coffee(fun3):
found=False
search =input('Enter a description to search for: ')
coffee_file=open('coffee.txt', 'r')
descr=coffee_file.readline()
while descr != '':
qty= float(coffee_file.readline())
descr = descr.rstrip('\n')
if descr== search:
print('Description:', descr)
print('Quantity:', qty)
found=True
descr=coffee_file.readline()
fun=fun3
return fun
coffee_file.close()
if not found:
print('That item was not found in the file.')
def modify_coffee(fun4):
found=False
search=input('Which coffee do you want to delete? ')
coffee_file=open('coffee.txt', 'r')
temp_file=open('temp.txt', 'w')
descr=coffee_file.readline()
while descr != '':
qty=float(coffee_file.readline())
descr=descr.rstrip('\n')
if descr !=search:
temp_file.write(descr + '\n')
temp_file.write(str(qty) + '\n')
else:
found=True
descr=coffee_file.readline()
fun=fun4
return fun
coffee_file.close()
temp_file.close()
os.remove('coffee.txt')
os.rename('temp.txt', 'coffee.txt')
if found:
print('The file has been update.')
else:
print('The item was not found in the file.')
def menu():
print('''
0. Add or Update an entry
1. Show an entry
2. Search
3. remove
4. Remove number
''')
def getUserChoice():
choice=-1
while choice <0 or choice > 3:
print("Please select 0-3: ",end='')
choice=int(input())
return choice
You are defining functions but this does not call a function. The standard way to do this in Python is use the if __name__=="__main__": statement at the bottom of a file. When the file is executed (instead of functions/classes being imported by another script) the code block within the scope of if __name__=="__main__": is executed.
Get comfortable with this, it's useful and clean :) Good read - What does if __name__ == "__main__": do?
So, for example...
At the bottom of your file...
if __name__=="__main__":
main()