Reputation: 13
Here is the code:
import random
import sys
name = input("What is your name: ")
tri = 0
def rep():
score = random.randint(1,10)
total = 0
print ("score is",score,)
total = +score
file = open("1.txt","a")
file.write(str(name + " = "))
file.write(str(total))
file.write("\n")
file.close()
tri = +1
rep()
while tri > 2:
sys.exit
else:
print(rep())
So what this code does, is generates a random score for the user 2 times and then that score is saved into a .txt file under the users name which is inputted as 'name'. What I want to do is, if the same person did the game again and another 2 scores where generated it would overwrite the previous 2 results with the new two.
Here is what the text file would look like:
Tom = 2
Tom = 7
Chrissy = 3
Chirssy = 10
John = 4
John = 9
If the the user 'Tom' did the game again this time getting 5 and 3, the text file should look like the following:
Chrissy = 3
Chirssy = 10
John = 4
John = 9
Tom = 5
Tom = 3
In this current situation it just keeps adding on the scores like this:
Tom = 2
Tom = 7
Chrissy = 3
Chirssy = 10
John = 4
John = 9
Tom = 5
Tom = 3
Upvotes: 1
Views: 1468
Reputation: 77337
This is an easy file format to just do by hand. The one issue is that text files aren't really stored as lines so you can't just modify just one line. Once you've changed a line, everything after that must be rewritten to the file. If the file isn't too big, you just read everything into a list and work off of that.
import random
def rep(name, score1, score2):
try:
# read entire file into list
with open('1.txt') as fp:
lines = fp.readlines()
except FileNotFoundError:
lines = []
name_lower = name.lower()
for index, line in enumerate(lines):
if line.split('=')[0].strip().lower() == name_lower:
# found our match... next line had better be the same player
if lines[index+1].split('=')[0].strip().lower() != name_lower:
raise RuntimeError("File corrupted")
# replace user in the list
lines[index] = "{} = {}\n".format(name, score1)
lines[index + 1] = "{} = {}\n".format(name, score2)
# no need to process further
break
else:
# add new user
lines.append("{} = {}\n".format(name, score1))
lines.append("{} = {}\n".format(name, score2))
with open('1.txt', 'w') as fp:
fp.writelines(lines)
name = input("what is your name: ")
rep(name, random.choice(range(100)), random.choice(range(100)))
print(open('1.txt').read()) # debug
Upvotes: 0
Reputation: 15924
A first comment, it's a really good idea to use the context managers for file operations, this will ensure that file resources are properly handled. For this reason I use it in the code here, I suggest you do the same.
If you are going to approach this in such a way that you want to use plain text files you have to remove the lines that contained the name then update. A function such as the following is likely going to help here:
def remove_old_names(name, filename):
"""Remove a line containing a specific name"""
with open(filename, 'r') as old_file:
lines = old_file.readlines()
with open(filename, 'w') as new_file:
for line in lines:
if name not in line:
new_file.write(line)
Then later when you can clear out the old names then append to the text file:
remove_old_names(name, filename)
with open("1.txt","a") as results:
results.write(str(name + " = "))
results.write(str(total))
results.write("\n")
Note the use of "a"
here to open the file in append mode. If you open with "w"
you can end up truncating the file.
Now if I was to approach this in a more structured way I would create a dictionary that stores the data:
results = dict()
results["bob"] = 2
And so forth for the other user names. I would then serialize this dictionary to a file using pickle
or the JSON library.
For example with JSON library you get something like this:
import json
test = {
"bob": 1,
"joe": 2,
"jane": 3,
}
print(json.dumps(test, sort_keys=True, indent=4))
output:
{
"bob": 1,
"jane": 3,
"joe": 2
}
Upvotes: 1