I am new to python (and programming in general) and am making a database/register for a typical class. I wanted the user to be able to add and remove pupils from the database, I used lists primarily for this but have hit a stump.
Whenever I restart the program the list the user has modified returns back to the defualt list I specified in the code. I looked around the internet and tried to save the list onto a seperate txt file. However the txt file also goes back to the defualt every time I restart the program. I would like you to please give me a way to save the changes made to the list and keep them that way. Here is the code (it's not very good):
def menu():
print "*****************CLASS REGISTER*****************"
print "Press 1 See The List Of Pupils"
print "Press 2 To Add New Pupils"
print "Press 3 To Remove Pupils"
print "Press 0 To Quit \n"
filename = open('pupil.txt','r')
pupil = ["James Steele", "Blain Krontick", "Leeroy Jenkins", "Tanvir Choudrey"]
def see_list(x):
print x
def add_pupil(x):
print "You have chosen to add a new pupil.\n"
option = raw_input("Please type the childs name.")
x.append(option)
filename = open('pupil.txt','w')
filename.write('\n'.join(pupil))
filename.close()
print option, "has been added to the system."
return x
def delete_pupil(x):
print "You have chosen to remove a pupil.\n"
option = raw_input("Please type the childs name.")
if option in x:
x.remove(option)
filename = open('pupil.txt','w')
filename.write('\n'.join(pupil))
filename.close()
print option, "has been removed from the system."
else:
print "That person is not in the system."
return x
one = 1
while one != 0:
menu()
option = input()
if option == 1:
see_list(pupil)
elif option == 2:
add_pupil(pupil)
elif option == 3:
delete_pupil(pupil)
elif option == 0:
break
else:
print "That is not a valible choice."
filename = open('pupil.txt','w')
filename.write('\n'.join(pupil))
filename.close()
if option == 0:
quit
Well, you just open the pupil.txt file but never read back its contents. You need something like this:
filename = open('pupil.txt', 'r')
contents = filename.read()
filename.close()
pupil = [name for name in contents.split('\n') if name]
Also, you will need to handle the case when the pupil.txt file does not exist; this can be done with a try..except block around the IO calls.
Finally, as one of the comments has mentioned above, have a look at the pickle module, which lets you store a Python object in a file in Python's internal format (which is not really readable, but saves you a lot of hassle).
Not related to your question directly, but this:
one = 1
while one != 0:
...
is silly. All you need is:
while True:
...
This is what a database is for. Use sqlite - a simple file-based database the libraries for which come bundled with python.
Related
I am trying to create a python program to save my friends' birthdays and access them easily and check for birthdays each day(I am not great at remembering dates and I never use facebook), but when I add a new birthday it is only accessible until I end the program - it then disappears again. I have been struggling with this for a while now and would really appreciate help fixing the error. Thanks!
import time
import pickle
def main():
birthday_file = open('birthdays_dict.dat','ab')
birthday_doc = open('birthdays_dict.dat','rb')
birthdays = pickle.load(birthday_doc)
date = time.strftime("%m/%d")
again = 'y'
while again.lower() == 'y' or again.lower() == 'yes':
choice = menu_choice()
if choice == 1:
name = add_name()
birthday = add_birthday()
birthdays[name] = birthday
print(name)
print(birthday)
pickle.dump(birthdays,birthday_file)
elif choice == 2:
print('Birthdays today(' + date + '):')
birth_today = {}
for key, value in birthdays.items():
if value == date:
print(key)
elif choice == 3:
search_name = input('Enter name to search: ')
print()
if search_name in birthdays:
print(birthdays[search_name])
if birthdays[search_name] == date:
print('Their birthday is today!')
else:
print('Not found')
else:
print('Not a valid selection!')
print()
again = go_again()
birthday_file.close()
birthday_doc.close()
Your problem is that you keep appending new dicts onto the file instead of replacing the old one, but then at startup you only load the very first one instead of all of them.
To fix this, you need to change this:
birthday_file = open('birthdays_dict.dat','ab')
… to this:
birthday_file = open('birthdays_dict.dat','wb')
But don't do that change on its own, because that will erase the file before you've read the old version!
You probably want to do something like this at the top of the function:
with open('birthdays_dict.dat', 'rb') as birthday_doc:
birthdays = pickle.load(birthday_doc)
I used a with statement so the file will automatically get closed right after the load, so it's definitely safe for us to overwrite it later.
Then later, when you want to write to the file, that's when you open it in w mode to erase the file and overwrite it with the new version—at which point you might as well close it immediately, because if you ever do write to it again, you're going to want to erase it again first, so let's use with again:
with open('birthdays_dict.dat', 'wb') as birthday_doc:
pickle.dump(birthdays, birthday_doc)
So for my intro programming class we have to create a game with a save/load function and I'm trying to test out some code to make sure it works.
For some reason I cannot get the following function to work properly. I've tried going through it line by line in the Idle and it works just fine there but once I try to use the same system in a function it just will not work. Help please?
def save(name,inventory,mapGrid,x,y,enemy):`
choice = 0
file = shelve.open("save_files")
save = {'save1':file['save1'],'save2':file['save2'],'save3':file['save3']}
print("Where would you like to save?")
print("Save 1 -", save['save1']['name'])
print("Save 2 -", save['save2']['name'])
print("Save 3 -", save['save3']['name'])
choice = input("Enter Number:\t")
if choice == 1:
save['save1']['name'] = name
save['save1']['inventory'] = inventory
save['save1']['mapGrid'] = mapGrid
save['save1']['x'] = x
save['save1']['y'] = y
save['save1']['enemy'] = enemy
file['save1'] = save['save1']
file.sync()
if choice == 2:
save['save2']['name'] = name
save['save2']['inventory'] = inventory
save['save2']['mapGrid'] = mapGrid
save['save2']['x'] = x
save['save2']['y'] = y
save['save2']['enemy'] = enemy
file['save2'] = save['save2']
file.sync()
if choice == 3:
save['save3']['name'] = name
save['save3']['inventory'] = inventory
save['save3']['mapGrid'] = mapGrid
save['save3']['x'] = x
save['save3']['y'] = y
save['save3']['enemy'] = enemy
file['save3'] = save['save3']
file.sync()
file.close()
print("Game Saved")
EDIT: After running the function it should save the dictionary to file['save#'] and allow me to access the data later on, but the data doesn't save to the shelve file and when I try to access it again there's nothing there. ((Sorry should have put this in right off the bat))
For example if I run the save() function again it should display the name associated with the save file, but it just shows 'EMPTY'.
The basic thing I have the save_files set to is
file['save#'] = {'name':'EMPTY'}
Since your if statements are comparing int, make sure that choice is also an integer. It's possible that choice is actually a string, in which case none of the comparisons will be True. Basically:
choice = int(input("Enter Number:\t"))
Alternatively you could change all comparisons to strings, but the important thing is to assure type consistency in the comparisons
this is some simple code I wrote for a phonebook.
It does not seem to work though, and I do not know why.
I am very new to python, and I am sure there are many errors.
def startup(contactlist = {}):
print "Welcome to Contacts+\n"
print "Please enter your name"
name = raw_input()
print "Hi " + name + " would you like to check your existing contacts or make new ones?"
print "To make new contacts type in 'New'"
print "To check existing contacts type in 'Contacts'"
choose = ""
choose = raw_input()
if choose == "'New'" or choose == "'new'" or choose == "New" or choose == "new":
newcontact()
elif choose == "'Contacts'" or choose == "'contacts'" or choose == "Contacts" or choose == "contacts":
checkcontact()
def newcontact():
startup(contactlist = {})
print "To create a new contact please first input the name"
contactname = raw_input()
print "Next enter the phone number"
contactnumber = raw_input()
print "Contact created!"
contactlist[name] = number
def checkcontact():
startup(contactlist = {})
print contactlist
startup()
Have you tried to run this...?
This if/elif statement shouldn't be indented:
if choose == "'New'" or choose == "'new'" or choose == "New" or choose == "new":
newcontact()
elif choose == "'Contacts'" or choose == "'contacts'" or choose == "Contacts" or choose == "contacts":
checkcontact()
And why do you have:
startup(contactlist = {})
in the beginning of newcontact() and checkcontact() function?
Four things you can do right now to make your code better:
Go read about this gotcha in Python. We tricked you. (We're sorry! We had good reasons.) You can't really do that with lists and dicts, and you have to use a Python idiom involving None to do it right.
Use raw_input's first argument. Instead of print('Hey user!'); raw_input(), just write raw_input('Hey user!').
Learn the in keyword. Whenever you find yourself saying if x == 'x' or x == 'y' or x == 'z', it's probably easier to write if x in 'xyz' (strings are iterable, remember?). You can also get rid of two of those cases by stripping off quotes the user might enter if you don't want them -- choose.strip("'").
Fix your function calls. Functions in Python can be called in two ways, using positional arguments f(a, b, c) or keyword arguments f(a, b=0, c=2). Calls like startup(contactlist={}) are just explicitly setting that argument to the empty dict, its default value, so this is always equivalent to startup() the way you have it defined.
Hello I am making a game out of python, and I made the game write data on a text document, and is there a way I can code so if the text file says a person named Bob is on level 4, then make the program start on level 4. I have tried using for loop to do the job, but it wont work. It will not initiate the text file and just goes over to level 1.
Here is the game code(for reading and writing:
import os
#---------------------------
os.system("color a")
#---------------------------
def ping(num):
os.system("ping localhost -i", num, ">nul")
def cls():
os.system("cls")
#--------------------------
print("the game")
ping(2)
cls()
print("1: New Game")
print("2: Continue")
print("3: Credits")
while True:
choice=input("Enter")
if choice==1:
name=input("Enter your name")
firstsave=open("data.txt", "W")
firstsave.write(name, " ")
# there will be the game data here
elif choice==2:
opendata=file("data")
#opening the file
while True:
''' is the place where the file scanning part needs to come.
after that, using if and elif to decide which level to start from.(there are a total of 15 levels in the game)
'''
The text file:
User Level
Bob 5
George 12
You haven't given quite enough information, but here's one approach:
elif choice == 2:
with open("x.txt") as f:
f.readline() # skip the first line
for lines in f: # loop through the rest of the lines
name, level = line.split() # split each line into two variables
if name == playername: # assumes your player has entered their name
playlevel(int(level)) # alternatively: setlevel = level or something
break # assumes you don't need to read more lines
This assumes several things, like that you know the player name, and that the player has only one line, the name is just a single word, etc. Gets more complicated if things are different, but that's what reading the Python documentation and experimenting is for.
Also note that you use 'w' to write in choice 1, which will (over)write rather than append. Not sure if you meant it, but you also use different filenames for choice 1 and 2.
I've just undertaken my first proper project with Python, a code snippet storing program.
To do this I need to first write, then read, multiple lines to a .txt file. I've done quite a bit of googling and found a few things about writing to the file (which didn't really work). What I have currently got working is a function that reads each line of a multiline input and writes it into a list before writing it into a file. I had thought that I would just be able to read that from the text file and add each line into a list then print each line separately using a while loop, which unfortunately didn't work.
After going and doing more research I decided to ask here. This is the code I have currently:
'''
Project created to store useful code snippets, prehaps one day it will evolve
into something goregous, but, for now it's just a simple archiver/library
'''
#!/usr/local/bin/python
import sys, os, curses
os.system("clear")
Menu ="""
#----------- Main Menu ---------#
# 1. Create or edit a snippet #
# 2. Read a snippet #
# 0. Quit #
#-------------------------------#
\n
"""
CreateMenu ="""
#-------------- Creation and deletion --------------#
# 1. Create a snippet #
# 2. Edit a snippet #
# 3. Delete a snippet (Will ask for validation) #
# 0. Go back #
#---------------------------------------------------#
\n
"""
ReadMenu="""
#------ Read a snippet ------#
# 1. Enter Snippet name #
# 2. List alphabetically #
# 3. Extra #
# 0. Go Back #
#----------------------------#
"""
def readFileLoop(usrChoice, directory):
count = 0
if usrChoice == 'y' or 'n':
if usrChoice == 'y':
f = open(directory, 'r')
text = f.read()
f.close()
length = len(text)
print text
print length
raw_input('Enter to continue')
readMenu()
f.close()
elif choice == 'n':
readMenu()
def raw_lines(prompt=''):
result = []
getmore = True
while getmore:
line = raw_input(prompt)
if len(line) > 0:
result.append(line)
else:
getmore = False
result = str(result)
result.replace('[','').replace(']','')
return result
def mainMenu():
os.system("clear")
print Menu
choice = ''
choice = raw_input('--: ')
createLoop = True
if choice == '1':
return creationMenu()
elif choice == '2':
readMenu()
elif choice == '0':
os.system("clear")
sys.exit(0)
def create():
os.system("clear")
name = raw_input("Enter the file name: ")
dire = ('shelf/'+name+'.txt')
if os.path.exists(dire):
while os.path.exists(dire):
os.system("clear")
print("This snippet already exists")
name = raw_input("Enter a different name: ")
dire = ('shelf/'+name+'.txt')
print("File created\n")
f = open(dire, "w")
print("---------Paste code below---------\n")
text = raw_lines()
raw_input('\nEnter to write to file')
f.writelines(text)
f.close()
raw_input('\nSnippet successfully filled, enter to continue')
else:
print("File created")
f = open(dire, "w")
print("---------Paste code below---------\n")
text = raw_lines()
print text
raw_input('\nEnter to write to file')
f.writelines(text)
f.close()
raw_input('\nSnippet successfully filled, enter to continue')
def readMenu():
os.system("clear")
name = ''
dire = ''
print ReadMenu
choice = raw_input('--:')
if choice == '1':
os.system("clear")
name = raw_input ('Enter Snippet name: ')
dire = ('shelf/'+name+'.txt')
if os.path.exists(dire):
choice = ''
choice = raw_input('The Snippet exists! Open? (y/n)')
'''if not choice == 'y' or 'n':
while (choice != 'y') or (choice != 'n'):
choice = raw_input('Enter \'y\' or \'n\' to continue: ')
if choice == 'y' or 'n':
break'''
readFileLoop(choice, dire)
else:
raw_input('No snippet with that name exists. Enter to continue: ') #add options to retry, create snippet or go back
readMenu()
elif choice == '0':
os.system("clear")
print Menu
def creationMenu(): ###### Menu to create, edit and delete a snippet ######
os.system("clear")
print CreateMenu
choice = raw_input('--: ')
if choice == '1': ### Create a snippet
os.system("clear")
print create()
print creationMenu()
elif choice == '2':
os.system("clear") ### Edit a snippet
print ("teh editon staton")
raw_input()
print creationMenu()
elif choice == '3':
os.system("clear") ### Delete a snippet
print ("Deletion staton")
raw_input()
print creationMenu()
elif choice == '0': ### Go Back
os.system("clear")
######## Main loop #######
running = True
print ('Welcome to the code library, please don\'t disturb other readers!\n\n')
while running:
mainMenu()
######## Main loop #######
Tl;Dr: Need to write and read multiline text files
The problem that I'm having is the way the multilines are being stored to the file, it's stored in list format e.g ['line1', 'line2', 'line3'] which is making it difficult to read as multilines because I can't get it to be read as a list, when I tried it added the whole stored string into one list item. I don't know if I'm writing to the file correctly.
OK, so the problem is with writing the file. You're reading it in correctly, it just doesn't have the data you want. And the problem is in your raw_lines function. First it assembles a list of lines in the result variable, which is good. Then it does this:
result = str(result)
result.replace('[','').replace(']','')
There are two small problems and one big one here.
First, replace:
Return[s] a copy of the string with all occurrences of substring old replaced by new.
Python strings are immutable. None of their methods change them in-place; all of them return a new string instead. You're not doing anything with that new string, so that line has no effect.
Second, if you want to join a sequence of strings into a string, you don't do that by calling str on the sequence and then trying to parse it. That's what the join method is for. For example, if your lines already end with newlines, you want ''.join(result). If not, you want something like '\n'.join(result) + '\n'. What you're doing has all kinds of problems—you forgot to remove the extra commas, you will remove any brackets (or commas, once you fix that) within the strings themselves, etc.
Finally, you shouldn't be doing this in the first place. You want to return something that can be passed to writelines, which:
Write[s] a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings.
You have a list of strings, which is exactly what writelines wants. Don't try to join them up into one string. If you do, it will run, but it won't do the right thing (because a string is, itself, a sequence of 1-character strings).
So, if you just remove those two lines entirely, your code will almost work.
But there's one last problem: raw_input:
… reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
But writelines:
… does not add line separators.
So, you'll end up with all of your lines concatenated together. You need the newlines, but raw_input throws them away. So, you have to add them back on. You can fix this with a simple one-line change:
result.append(line + '\n')
To read multiple lines from a file, it's easiest to use readlines(), which will return a list of all lines in the file. To read the file use:
with open(directory, 'r') as f:
lines = f.readlines()
And to write out your changes, use:
with open(directory, 'w') as f:
f.writelines(lines)
fileList = [line for line in open("file.txt")]
While the previously mention idiom will work for reading files, I like mine. Its short and to the point.