Reputation: 43
I'm trying to save the answers from a GUI that has radio buttons that has different value ranging from A, B and C, but when I'm trying my code it completely rewrite the first letters and not going to the next line.
self.pushButton.clicked.connect(lambda:
self.btnA_clk(self.radioButton_16.isChecked()))
self.pushButton.clicked.connect(lambda:
self.btnB_clk(self.radioButton_17.isChecked()))
self.pushButton.clicked.connect(lambda:
self.btnC_clk(self.radioButton_18.isChecked()))
def btnA_clk(self, clkA):
if clkA:
textfile = open("studentexam.txt", "w")
print("A")
textfile.write("A")
textfile.close()
def btnB_clk(self, clkB):
if clkB:
textfile = open("studentexam.txt", "w")
print("B")
textfile.write("B")
textfile.close()
def btnC_clk(self, clkC):
if clkC:
textfile = open("studentexam.txt", "w")
print("C")
textfile.write("C")
textfile.close()
My output in my console is a b c d e but in the text file it has only 1 letter written in the first line which is the last letter.
Upvotes: 0
Views: 31
Reputation: 16941
Every time your code does this:
textfile = open("studentexam.txt", "w")
you are opening the file afresh and overwriting what was there before. The same as File | Save does in an application, except that your code doesn't ask "Are you sure?". Use mode "a"
instead of "w"
.
From the documentation for open():
The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending.
Upvotes: 3
Reputation: 898
# param = 'clkA'
def button_click(self, param):
with open('studentexam.txt', 'a') as f:
print(param[-1])
f.write(param[-1])
Confused by python file mode "w+"
ps. try to avoid duplication of the code when each function does same functionality ... if possible of course.
Upvotes: 0