Appending Variable To Text File Not Working In Python
Solution 1:
ClassOfStudent
is a string rather than a number, so none of the code that writes to the file will get executed. You can easily verify that by adding a print
statement under each if
so you can see if that code is being executed.
The solution is to compare to strings, or convert ClassOfStudent
to an i teger.
Solution 2:
Use print(repr(ClassOfStudent))
to show the value and type:
>>>ClassOfStudent = input("Which class are you in?")
Which class are you in?2
>>>print(repr(ClassOfStudent))
'2'
Using input()
in Python 3 will read the value in as a string. You need to either convert it to an int
or do the comparison against a string.
ClassOfStudent = int(input("Which class are you in?")
should fix your problem.
Solution 3:
first you have a problem with the "". you have to correct the following:
if ClassOfStudent==2: #write scores to class 1 text
file_var = open("Class 2.txt",'w+')
file_var.write("name, score")
file_var.close()
if ClassOfStudent==3: #write scores to class 1 text
file_var = open("Class 3.txt",'w+')
file_var.write("name, score")
file_var.close()
notice that I added the "" inside the write. In any case, I think what you want is something like: file_var.write("name %s, score %s"%(name,score)). This should be more appropriate.
Post a Comment for "Appending Variable To Text File Not Working In Python"