How do I save data in a text file python - python

So I am making a simple randomized number game, and I want to save the players High Score even after the program is shut down and ran again. I want the computer to be able to ask the player their name, search through the database of names in a text file, and pull up their high score. Then if their name is not there, create a name in the database. I am unsure on how to do that. I am a noob programmer and this is my second program. Any help would be appreciated.
Here is the Code for the random number game:
import random
import time
def getscore():
score = 0
return score
print(score)
def main(score):
number = random.randrange(1,5+1)
print("Your score is %s") %(score)
print("Please enter a number between 1 and 5")
user_number = int(raw_input(""))
if user_number == number:
print("Congrats!")
time.sleep(1)
print("Your number was %d, the computers number was also %d!") %(user_number,number)
score = score + 10
main(score)
elif user_number != number:
print("Sorry")
time.sleep(1)
print("Your number was %d, but the computers was %d.") %(user_number, number)
time.sleep(2)
print("Your total score was %d") %(score)
time.sleep(2)
getscore()
score = getscore()
main(score)
main(score)
EDIT:
I am trying this and it seems to be working, except, when I try to replace the string with a variable, it gives an error:
def writehs():
name = raw_input("Please enter your name")
a = open('scores.txt', 'w')
a.write(name: 05)
a.close()
def readhs():
f = open("test.txt", "r")
writehs()
readhs()

with open('out.txt', 'w') as output:
output.write(getscore())
Using with like this is the preferred way to work with files because it automatically handles file closure, even through exceptions.
Also, remember to fix your getscore() method so it doesn't always return 0. If you want it to print the score as well, put the print statement before the return.

In order to write a file using python do the following:
file2write=open("filename",'w')
file2write.write("here goes the data")
file2write.close()
If you want to read or append the file just change 'w' for 'r' or 'a' respectively

First of all you should ask your question clearly enough for others to understand.To add a text into text file you could always use the open built-in function.Do it like this.
>>> a = open('test.txt', 'w')
>>> a.write('theunixdisaster\t 05')
>>> a.close()
Thats all.If need further help try this website.
http://www.afterhoursprogramming.com/tutorial/Python/Writing-to-Files/
You could also use a for loop for the game to print all the scores.
Try this one on your own.It would rather be fun.
THE RECOMENDED WAY
Well as if the recommended way use it like this:
>>> with open('test.txt', 'w') as a:
a.write('theunixdisaster\t 05')
With this its certain that the file would close.
With variables
>>> name = sempron
>>> with open('test.txt', 'w') as a:
a.write('%s: 05' % name)
Now try calling it.Well I use python 3.4.2.So, if you get into errors, try to check if there is any difference in the string formatting with the python version that you use.

Related

local variable 'output_file' referenced before, this code worked a few weeks ago, now it doesnt work how is that possible?

This thing is hard to post code and context inside of.
#This is a menu driven multiplication game. i am attemtping to save the high
#score in a file named multiplication_game.txt...
def single_player():
in_file = open('multiplication_game.txt', 'r')
highest_times_selection = int(in_file.readline())
print('\n____now lets see how u do on the times tables____')
correct = 0
missed = 0
times_selection = int(input(
'\nPlease enter a times time table integer to practice: '))
#This simple generates the multiplation questions and checks for right or
#wrong.
for number in range(0,11):
print(times_selection, 'x' , number, '=')
user_answer=int(input('answer: '))
correct_answer = times_selection * number
if user_answer == correct_answer:
correct+=1
else:
missed+=1
#This is where if its a perfect score and a high times table than the
#previous saved score it should be opened and the new score saved in the
#text document.
if missed == 0 and times_selection > highest_times_selection :
output_file = open('multiplication_game.txt', 'w')
name = input('You have the highest Score!!\n enter your name: ')
output_file.write(str(times_selection)+ '\n')
output_file.write(name + '\n')
else:
print('you missed ', missed, 'and got', correct,'correct\n')
output_file.close()
Try to define output_file = None before any assignment of it.
Tip: before your last if-else condition.
This looks like homework, so I don't want to give you the answer but rather lead you to it.
Take a look at your if/else for your high score table, and walk through your code twice, taking a different branch (different part of the if/else) each time you reach this spot. Write down the variable names on paper as you define them, starting over with a new sheet of paper each time you walk through. If you access a variable, check it off on your list. If you try to access a variable that's not on your list, it's the same as python saying local variable referenced before assignment -- you're trying to access it before you've defined it.
Hope this helps, both in figuring out your problem and learning how to debug in the future.

I'm trying to put these inputs into a text file, [duplicate]

This question already has answers here:
Print string to text file
(8 answers)
Closed 6 years ago.
In class we are working on functions that calculate the area of a square or rectangle. The program asks for a person's name, what shape they want and what the length and width are. It then prints the area of that shape, and the program loops back around again. What I'm looking to do is take each individual name input and area and output them into a text file. Our teacher didn't make it too clear on how to do this. Any help would be appreciated. Here's the code:
import time
def area(l, w):
area = l * w
return area
def square():
width = int(input("please enter the width of the square"))
squareArea = area(width, width)
return squareArea
def rectangle():
width = int(input("please enter the width of the rectangle"))
length = int(input("please enter the length of the rectangle"))
rectangleArea = area(length, width)
return rectangleArea
def main():
name = input("please enter your name")
shape = input("please enter s(square) or r(rectangle)")
if shape == "r" or shape =="R":
print ("area =", rectangle())
main()
elif shape == "s" or shape == "S":
print ("area =", square())
main()
else:
print ("please try again")
main()
main()
Edit: I don't think I asked the question clear enough, sorry. I want to be able to input something, e.g. the name and be able to put it into a text file.
Easy way:
file_to_write = open('myfile', 'w') # open file with 'w' - write permissions
file_to_write.write('hi there\n') # write text into the file
file_to_write.close() # close file after you have put content in it
If you want to ensure that a file is closed after you finished all operations with it use next example:
with open('myfile.txt', 'w') as file_to_write:
file_to_write.write("text")
This is what you're looking for. The line file = open('file.txt', 'w') creates a variable file, in which the file object representing 'file.txt' is stored. The second argument, w, tells the function to open the file in "write mode", allowing you to edit its contents.. Once you have done this, you can simply use f.write('Bla\n') to write to the file. Of course, replace Bla with whatever you'd like to add, which can be your string variable. Note that this function doesn't make a newline afterwards by default, so you'll need to add a \n at the end if that's what you want.
IMPORTANT: As soon as you're done with a file, make sure to use file.close(). This will remove the file from memory. If you forget to do this, it won't be the end of the world, but it should always be done. Failure to do this is a common cause of high memory usage and memory leaks in beginner programs.
Hope this helps!
Edit: As MattDMo mentioned, it is best practice to open a file using a with statement.
with open("file.txt", 'w') as file:
# Work with data
This will make absolutely sure that access to the file is isolated to this with statement. Thanks to MattDMo to for reminding me of this.

comparing files which i created by python

I have created files using python, which I need to compare. How can I compare the two files using python?
def td():
choice = input("which trainning event would you like to access?
\n1.swimming
\n2.cycling
\n3.running\nplease type in the number before the event of which you want to choose\n")
if choice == "1":
Swimming_file= open("Swimming_file.txt", "w")
totaldistance = input("what was the total distance you swam in meters?")
totaltime = input("how long did you swim for in minutes?")
speed = totaldistance/totaltime
print ("on average you where running at a speed of", speed, "mps")
total = (totaldistance, totaltime, speed)
Swimming_file.write(str(total))
Swimming_file.close()
elif choice == "3":
Running_file= open("Running_file.txt", "w")
totaldistanceR = int(input("what was the total distance you ran in KM?"))
totaltimeR = int(input("how long did you run for in minutes?"))
totaltimeR1 = 60/totaltimeR
speedR1 = totaldistanceR/totaltimeR1
print ("The records have been saved")
print ("on average you where running at a speed of", speedR1, "KMph")
totalR = (totaldistanceR, totaltimeR, speedR1)
Running_file.write(str(totalR))
Running_file.close()
elif choice == "2":
Cycling_file= open("Cycling_file.txt", "w")
totaldistancec = int(input("what was the total distance you ran in KM?"))
totaltimec = int(input("how long did you run for in minutes?"))
speedc = totaldistancec/totaltimec
print ("on average you where running at a speed of", speedc, "KMph")
totalc = (totaldistancec, totaltimec, speedc)
Cycling_file.write(str(totalc))
Cycling_file.close()
The created files contain running times named after the username. I need to compare files so the user can see how fast other users are.
I have been looking on the internet for this solution but none are relevant to my problem.
I think you first need to update your question. if you would like to compare two files you can do it this way:
from __future__ import with_statement
with open(filename1) as f1:
with open(filename2) as f2:
if f1.read() == f2.read():
...
Or This way
import filecmp
if filecmp.cmp(filename1, filename2, shallow=False):
...
But you do not say what you would like clearly, what exactly are you comparing, are you comparing information inside the files with different username and times? How is the files structured. Do you need to select one user first and then find at what place sorted by time that user is compared to other?
We will help you just as long as you write an excellent description.
EDIT after OP updated post: You still need to give information about your data. and are you sure your code runs like you have written,
speed = totaldistance/totaltime
You should maybe not do math on a string. and you are not saving username in the file, how should you compare data without information about whom has what time in a certain event?
could you maybe write what you are trying to do so we can help you better?
i'm not sure about your question but i think this is your answer:
U1 = open('file1.txt', 'r')
U2 = open('file2.txt', 'r')
username1 = U1.readline()
username2 = U2.readline()
if U1.readline() >= U2.readline():
#do something
else:
#do something else...

Python program doesn't quit; import random causing errors

Forgive me if this comes out a bit scatter-brained, I'm not exaggerating when I say I've been working on this program for over 13 hours now and I am seriously sleep deprived. This is my 4th revision and I honestly don't know what to do anymore, so if anyone can help me, it would be greatly appreciated. My introduction to programming teacher wanted us to make a "flash card" study program from his template. I am using Idle 3.3.3 on a windows 7 machine.
#Flash Cards
#Uses parallel arrays to store flash card data read from file
#Quizzes user by displaying fact and asking them to give answer
import random
def main():
answer = [] #array to store answer for each card
fact = [] #array to store fact/definition for each card
totalTried = 0 #stores number of cards attempted
totalRight = 0 #stores number of correct guesses
loadCards(answer, fact) #call loadcards() and pass it both arrays
numCards = len(answer) #find number of cards loaded
keepGoing = "y"
while keepGoing == "y" or keepGoing == "Y":
#Enter your code below this line
# 2a. Pick random integer between 0 and numCards and store the
# number in a variable named randomPick.
randomPick = random.randint (0, numCards)
# 2b. Add one to the totalTried accumulator variable.
totalTried = totalTried + 1
# 2c. Print element randomPick of the fact array. This shows the
# user the fact/definition for this flashcard.
print (fact [randomPick] )
# 2d. Prompt the user to input their guess and store the string they
# enter in a variable named "userAnswer"
userAnswer = input ('What is your answer?' )
# 2e. Compare the user's guess -userAnswer- to element
# -randomPick- of the answer array.
if userAnswer == (answer [randomPick]):
# 2e-1 If the two strings are equal, tell the user they
# guessed correctly and add 1 to the totalRight
# accumulator variable.
print ('That is correct.')
totalRight == totalRight + 1
# 2e2. If the two strings are not equal, tell the user they guessed
# wrong and display the correct answer from the answer array.
else:
print ('That is incorrect.')
print (answer [randomPick])
#2f. Prompt the user the user to see if they want to continue and
#store their response in the keepGoing variable.
keepGoing = input ('Would you like to continue?')
#Enter your code above this line
print("You got", totalRight, "right out of", totalTried, "attempted.")
def loadCards(answer, fact):
#Enter your code below this line
# 1a. Open flashcards.txt in read mode & assign it var name "infile"
infile = open('flashcards.txt', 'r')
# 1b. Read 1st line from file and store in var. name "line1"
line1 = infile.readline ()
# 1c. Use while loop to make sure EoF has not been reached.
while line1 != '':
# 1c1. Strip newline escape sequence (\n)from variable's value.
line1 = line1.rstrip ('\n')
# 1c2. Append string to answer array.
answer.append (line1)
# 1c3. Read next line from file and store in var. name "line2"
line2 = infile.readline ()
# 1c4. Strip newline escape sequence (\n) from variable's value.
line2 = line2.rstrip ('\n')
# 1c5. Append the string to the fact array.
fact.append (line2)
# 1c6. Read next line from file and store it in var. name "line3".
line3 = infile.readline ()
# 1d. Close file.
infile.close()
#Enter your code above this line
main()
When I run the program nothing actually happens, but when I try to close the shell window afterwards, it tells me that the program is still running and asks if I want to kill it.
Debugger shows me no information when I try to check it, also.
However, if I copy the code into the shell and run it from there, I get "SyntaxError: multiple statements found while compiling a single statement". Neither file has changed, but earlier it was telling me there was a problem with "import random".
Thanks in advance for any help.
I took a quick look and it mostly seems okay to me. I changed input() to raw_input() (two of them in your code) and noticed you had a double equals when you probably meant a single one
line 36:
totalRight == totalRight + 1
changed to
totalRight = totalRight + 1
which fixes your correct answer counter and line 68:
line3 = infile.readline ()
changed to
line1 = infile.readline ()
else it gets caught in your while loop forever. And I just copied line 54:
line1 = infile.readline ()
and pasted it so it is there twice to add another readline() call, just a lazy way of skipping the first line in your text file, since it seems to be a comment and not part of the answers and questions. You probably don't want to do that and just remove the comment from your text file. =b
With those changes, it seems to work fine for me.
Since this is for a class (and I can't only comment, I can just answer) I want to add that there actually is such a thing as too many comments
These comments (and to be honest, most of your comments) are distracting and unnecessary
answer = [] #array to store answer for each card
fact = [] #array to store fact/definition for each card
totalTried = 0 #stores number of cards attempted
totalRight = 0 #stores number of correct guesses
loadCards(answer, fact) #call loadcards() and pass it both arrays
numCards = len(answer) #find number of cards loaded
Also, the whole point of putting your program inside of a function called main is so you can run that function only if you are calling that file directly and you should probably put
if __name__ == '__main__':
main()
at the bottom of your code instead of just
main()
Use of input() is generally considered dangerous (unless you're using Python3 or later where it is the same as raw_input()) due to the fact that it evaluates the input. You should handle the type yourself with something like, if you want an integer,
foo = int(raw_input('Input a number: '))
(Note that the return of raw_input is a string, so if you want a string you don't have to do anything)

Sort a list that was imported from a file... Python

I am very new to python, and I am hoping I didnt miss a fix for this somewhere else. I have a simple program that was one of the practice excercises in a book I purchased and I am running into an issue. I have a program that opens a file and writes it to a list. Then a user can update the list with input, and when a user exits it updates the list with the latest content. Everything works fine except the sort option. It shows the scores from the file with a single quote infront of them, and the scores updated while the program was running without. It also doesn't sort them at all. I have tried many different way to do this without fail. I am sure this is not that important in the long run, but I wanted to figure it out.
Here is the code
# High Scores
# Demonstrates list methods
scores = []
try:
text_file = open("scores.txt", "r")
for line in text_file:
scores.append(line.rstrip("\n"))
text_file.close()
except:
raw_input("Please verify that scores.txt is placed in the correct location and run again")
choice = None
while choice != "0":
print \
"""
High Scores Keeper
0 - Exit
1 - Show Scores
2 - Add a Score
3 - Delete a Score
4 - Sort Scores
"""
choice = raw_input("Choice: ")
print
# exit
if choice == "0":
try:
output_file = open("scores.txt" , "w")
for i in scores:
output_file.write(str(i))
output_file.write("\n")
output_file.close()
print "Good-bye"
except:
print "Good-bye.error"
# list high-score table
elif choice == "1":
print "High Scores"
for score in scores:
print score
# add a score
elif choice == "2":
score = int(raw_input("What score did you get?: "))
scores.append(score)
# delete a score
elif choice == "3":
score = int(raw_input("Delete which score?: "))
if score in scores:
scores.remove(score)
else:
print score, "isn't in the high scores list."
# sort scores
elif choice == "4":
scores.sort()
scores.reverse()
print scores
# some unknown choice
else:
print "Sorry, but", choice, "isn't a valid choice."
raw_input("\n\nPress the enter key to exit.")
When you add scores from the file, you're adding them as strings: scores.append(line.rstrip("\n")). But when you add scores during the program, you're adding them as integers: int(raw_input("What score did you get?: ")).
When Python sorts a list containing both strings and integers, it'll sort the strings according to character order (so '1' < '12' < '3'), and sort the integers separately, putting the integers before the strings:
>>> sorted([1, 8, '11', '3', '8'])
[1, 8, '11', '3', '8']
Presumably it's printing out a single quote after the characters as well as before, as it does here (indicating that it's a string).
So, when you're reading the file at the start, turn them into an integer just like you do when you read user input.
Some other tips:
scores.sort(reverse=True) will sort in reverse order without having to go through the list twice.
It's generally a bad idea to do except:: that'll catch absolutely any problem with the program, including the user hitting ^C to try to quit, the system running out of memory, etc. You should do except Exception: as a catch-all to get exceptions that it's possible to recover from but not those kinds of system errors, or a more specific exception when you want to handle only certain types.
If in your text file you have only one score per line, the best way is to change the scores into integers while taking inputs like this.
scores = []
try:
text_file = open("scores.txt", "r")
for line in text_file:
scores.append(int(line.strip()))
except:
text_file.close()
Actually the way you are taking inputs is leaving some of your numbers as strings. The best way to deal with these types of problems is to print the array before sorting and look into it. All the best.

Categories