我撰寫了一個接受用戶輸入并將其保存為文本檔案的代碼。
from tkinter import *
def save_info():
question_info = question.get()
choices_info = choices.get()
correct_answer_info = correct_answer.get()
marks_info = marks.get()
time_info = time.get()
#print('all values')
file = open("user.txt","w")
file.write(question_info)
file.write("\n")
file.write(choices_info)
file.write("\n")
file.write(correct_answer_info)
file.write("\n")
file.write(str(marks_info))
file.write("\n")
file.write(str(time_info))
file.close()
app = Tk()
app.geometry("600x600")
app.title("Assesment Question")
heading = Label(text="Enter the Asked Information",fg="black",bg="yellow",width="500",height="3",font="10")
heading.pack()
question_text = Label(text="Question")
choices_text = Label(text="Choices separated by #")
correct_answer_text = Label(text="Correct Answer")
marks_text = Label(text='Marks')
time_text = Label(text="Time in seconds")
question_text.place(x=15,y=70)
choices_text.place(x=15,y=140)
correct_answer_text.place(x=15,y=210)
marks_text.place(x=15,y=280)
time_text.place(x=15,y=350)
question = StringVar()
choices = StringVar()
correct_answer = StringVar()
marks = IntVar()
time = IntVar()
question_entry = Entry(textvariable=question,width="30")
choices_entry = Entry(textvariable=choices,width="30")
correct_answer_entry = Entry(textvariable=correct_answer,width="30")
marks_entry = Entry(textvariable=marks,width="30")
time_entry = Entry(textvariable=time,width="30")
question_entry.place(x=15,y=100)
choices_entry.place(x=15,y=180)
correct_answer_entry.place(x=15,y=240)
marks_entry.place(x=15,y=300)
time_entry.place(x=15,y=380)
button = Button(app,text="Submit Data",command=save_info,width="30",height="2",bg="grey")
button.place(x=15,y=420)
mainloop()
現在,當我想將新資料添加到我的文本檔案時,值會被修改。
有什么辦法可以通過附加新資料而不是覆寫它來更新我的文本檔案?
我想要這樣的 txt 檔案中的輸出:
問題1
選擇1
正確答案1
標記1
時間1
問題2
選擇2
正確答案2
標記2
時間2
uj5u.com熱心網友回復:
當然有。使用file = open("user.txt","a"),如檔案所述。
print('\n'.join([question_info, choices_info, correct_answer_info, str(marks_info), (time_info)]), file=file)
我使用print它是因為它還添加了一個尾隨換行符,而您沒有這樣做。
或者:
print( f"{question_info}\n{choices_info}\n{correct_answer_info}\n{marks_info}\n{time_info}", file=file)
uj5u.com熱心網友回復:
這很簡單,只需使用
file = open("user.txt","a")
代替
file = open("user.txt","w")
這個“a”的作用是以附加模式打開檔案,這意味著它會將新資料與以前的資料一起添加到您的檔案中。如果您使用“w”寫入模式,它會添加新資料但會洗掉以前的資料。所以你最終只會得到你剛才輸入的資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/448491.html
