0

I am creating a quiz program, and i want to be able to save the users score to a text file. However my code that is supposed to write to a text file is not; the text file seems to be untouched. No errors are encountered.

with open("Class {0} data.txt".format(classNo),"r") as src:

        # list containing all data from file, one line is one item in list
        data = src.readlines()

        for ind,line in enumerate(data):

            if surname.lower() and firstName.lower() in line.lower():
                # overwrite the relevant item in data with the updated score
                data[ind] = "{0} {1}\n".format(line.rstrip(),score)
                rewrite = True

            else:
                with open("Class {0} data.txt".format(classNo),"a") as src: 
                    src.write("{0},{1} : {2}{3} ".format(surname, firstName, score,"\n"))

    if rewrite == True:
        # reopen src in write mode and overwrite all the records with the items in data
        with open("Class {} data.txt".format(classNo),"w") as src: 
            src.writelines(data)
    flag = False
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
joyalrj22
  • 115
  • 4
  • 12
  • Probably better to just remove the commented out code, since it's not relevant to your question. – Robert Harvey Jan 14 '15 at 21:11
  • 2
    `surname.lower()` is **always true**, so your `else` is never executed. If you wanted to test if both `surname` and `firstName` are found in `line` you'll have to do separate tests for both: `if surname.lower() in line.lower() and firstName.lower() in line.lower():`. – Martijn Pieters Jan 14 '15 at 21:13
  • @MartijnPieters but both conditions need to be met so i cant split it into if and elif, but if I use if surname.lower() in line.lower() and firstName.lower() in line.lower():the text file still remains untouched – joyalrj22 Jan 14 '15 at 21:19
  • @MartijnPieters Also this code seemed to work about a month ago – joyalrj22 Jan 14 '15 at 21:19
  • @joyalrj22: if the code worked a month ago then `surname` was an empty string; that's the only way the `if` test would actually ever be false for some lines. Next thing to check: does `data` actually contain anything or is it empty? – Martijn Pieters Jan 14 '15 at 21:20
  • @MartijnPieters Aha yes i am testing on an empty test file, so yes, data is empty - does that affect it at all? – joyalrj22 Jan 14 '15 at 21:23
  • 1
    **Of course** it does, because then your `for` loop has nothing to iterate over. No code in the loop will ever be executed. – Martijn Pieters Jan 14 '15 at 21:25

0 Answers0