0

My program is a maths quiz. The user completes 10 questions and then gets a score. That score then needs to be appended to the text file.

if classs == "1":
    text_file = open("Class1.txt", "r")
    data = text_file.read()
    text_file.close()
    if name in data:
        searchName(name, score)
    else:
        text_file = open("newFileName.txt","a")
        text_file.write(str(name) +","+ str(score)+ "\n")
        text_file.close()

    questions = 0
    score = 0
    break

This block of code appends that users score and name to the text file.

However I need to make it so if the user has already taken the quiz, the score is appended to that name instead of creating a new value. The score should be appended until there are three scores to one name, then if the quiz is taken again, it'll remove the first score and append the newest.

def searchName(name, score):
    with open("Class1.txt", 'r') as f:
        data = f.read().split('\n')
        print(data)
        with open("newFileName.txt", 'w') as newFile:
            for line in data:
                if name in line:        
                    line+=(',') + str(score) + (',')
                newFile.write(line + '\n')

But it only saves 1 score and removes it once the quiz is taken again.

Dion,0
Jarrod,1
Jake Bing,6
Charlie,2,5

Reverts to

Dion,0
Jarrod,1
Jake Bing,6,5
Charlie,2,

If another user uses the quiz (Jake Bing)

JJA
  • 5
  • 5
  • 5
    You can't append to lines in the middle of a file. You'll need to save the line, remove it, append the new data, then write it back – OneCricketeer Nov 30 '15 at 09:25

2 Answers2

0
def main():

data_file = open("C:\Users\sama0714\Test\\test.txt");

data = dict()
new_score = ("Jake Bing", 4)

for line in data_file.readlines():
    record = line.split(':')
    data[record[0]] = list(record[1].split(','))

try:
    data[new_score[0]].append(new_score[1])
except KeyError:
    data[new_score[0]] = list(str(new_score[1]))

data_file.close()

data_file =  open("C:\Users\sama0714\Test\\test.txt","w");
for name, scores in data.items():
    data_file.write(name + ":" + ",".join(str(i) for i in scores))

data_file.close()

as said in the comment read the entire file and change the data and write it back.

I am using dictionary here to accesses information of particular player to access data quickly, use can use any data handlers list or 'set` etc.

I have change the data structure in the file to be as following in order to create dictionary easily. (: separates name from scores)

Charlie:2,5

Dion:0

Jarrod:

Jake Bing:4

I have tried to eliminate KeyError failure in case this is the first attempt at whatever

saikumarm
  • 1,565
  • 1
  • 15
  • 30
0

The easiest way to handle this problem would probably be to create a dictionary for each class (although this would be vulnerable to issues if there are duplicate names in a class). For each name (dictionary key), you can create a list and append scores to the list. When you've finished processing the input, you can then write all of your scores at once. This would be more efficient than repeatedly reading and writing to files too. It might look something like this (create student_dict after your if classs... statement):

def search_name(name, score, student_dict):

    if name not in student_dict.keys():
        student_dict[name]=[]
    student_dict[name].append(score)

    return student_dict #{"student_name":[score_1,score2], ... }

When you've finished processing the scores you can then write the names and list of scores directly to a file in one step. Ideally, I'd do away with search_name altogether, and simply import all names and scores directly into a dictionary in one step and then write the dictionary to file in a second step. For more information on how to write dictionaries check out this. To find out how to convert a list to a string, have a look at this page. If you have any further questions, let me know.

Community
  • 1
  • 1
MarkyD43
  • 457
  • 4
  • 20