python - Maximum pieces of data appending to a file -
I have a piece of code that adds a user name and scores in a file but I was thinking How can I create it that only 10 names and scores can be on file at any time. My code is as follows:
def storecores (): hs = open ("hst.txt", "a") hs.write (name + ") hs.write (str (score) + "\ N") hs.close ()
Is there any way to do that if 10 names are already in the list then can not be added anymore? For some sort of sorting method (selection, bubble, etc.) is required, can you please also add it to?
First of all, whatever you do, it needs to read from the file up to 10 lines
If you want to keep the first 10 digits, then stop the new recording, it is easy. I will use the module for efficiency (so if you do storecores
Calling 1000 times in one line, it will be remembered that it is already searching and failed to find the 10th line). It will return an empty string if it has less than 10 lines or 10th row If 10 or more then:
def storecores (): If line cache Gateline ("hst.txt", 10): print ("10 scores have already been collected, sorry") returns H. Hs = open ("hst.txt", "a") hs.write (name + "") hs.write (str (score) + "\ n") hs.close ()
< / Pre>If you want the most recent 10 scores, then you will have to read in lines, then write a new file like this:
def storecores (): open ("hst .txt ") as hs: lines = list (hs) lines.append (name +" + + + + + "\ n") for lines line: hs.write (line)
< / Pre>If you want lines with lines ("hst.txt", "w") as lines [-10:] top 10 points, you can do the same thing But in the middle of the way There is no reason to write clear selection sort or bubble sort - and in fact, you do not want to do this because they are not the best sort algorithms in the first place.
sorting
Call the method.The hard bit is that you want to sort on the score , not the entire line (otherwise than "Bob 100" "Andrew 200" High score), and as a string On the score as the number (otherwise, "2" is more than "10") Therefore, you need to split the string, take the last bit, and change it to a number if:
def storecores (): open ("hst.txt") Hs: lines = list (hs) lines.append (name + "+ + + + +" \ n ") lines. Sort (key = lambda line: int (line.split () [- 1])) lines = Lines [-10:] open ("hst.txt", "w") as hs in: lines in line: h. Writing (line)
and more For example, instead of rewriting the file, you can create a new temporary file You might want to type in the URL, then when you do it, copy it to the file (so if someone pulls the plug between running your program, then you end up with the older versions, or instead of a small partial file, New). Or instead of re-ordering the fully ordered list, instead of re-ordering the position in the new fair score, you can use either the cleist way or the module to get new scores. Each (do not, when only 10 entries, it means a lot). And so on. But you must be enough to get it started.
Comments
Post a Comment