无法从Python写入文本文件

时间:2016-02-03 19:30:35

标签: python tkinter text-files

这可能很简单,但我仍然无法确定解决方案是什么。我有这段代码,它是来自较长代码的样本。

radio1Value = slotchoose.get()
if radio1Value == 0:
    with open ("test2.txt", "w") as file:
        file.write ("Slot : 9 AM - 10 AM")
    slot.remove("9 AM") 
    r12.destroy()
elif radio1Value == 1:
    slot.remove("10 AM")
    with open ("test2.txt", "w") as file :
        file.write ("Slot : 10 AM - 11 AM\n")
    r13.destroy()

checkValue = doctor.get()
if checkValue == 1:
    with open ("test2.txt", "w") as file :
        file.write ("\nDoctor : Dr. Adam Ahmed")
        payment = "RM100.00"
elif checkValue == 2:
    with open ("test2.txt", "w") as file :
        file.write ("Doctor : Dr Adib Kamal")
        payment = "RM200.00"

radioValue = specialistchoose.get()

if radioValue == 1 :
    with open ("test2.txt", "w") as file :
        file.write ("\nSpecialist : Cardiology")
elif radioValue == 2:
    with open ("test2.txt", "w") as file : 
        file.write ("Specialist : Gastroenterology")
elif radioValue == 3:
    with open ("test2.txt", "w") as file : 
        file.write ("Specialist : Dermatology")
elif radioValue == "Psychiatry":
    with open ("test2.txt", "w") as file : 
        file.write("Specialist : Psychiatry")
elif radioValue == "Dentist" :
    with open ("test2.txt", "w") as file: 
        file.write("Specialist : Dentist")

slotchoosedoctorspecialistchoose来自用户的输入,点击单选按钮和检查按钮。我尝试将字符串值添加到slotchoosedoctorspecialchoose,然后将其保存到文本文件中。但问题是我每次运行它并打开文本文件test2.txt时,它只会有specialistchoose值。

1 个答案:

答案 0 :(得分:3)

每次open()时都会覆盖该文件,因为这是模式w的作用。如果要累积多次写入文件的文本,则需要使用追加模式(a)。

Python 2 doc:

https://docs.python.org/2/library/functions.html#open

Python 3 doc:

https://docs.python.org/3/library/functions.html#open

  

mode是一个可选字符串,用于指定打开文件的模式。它默认为'r',表示在文本模式下打开。其他常见值为'w'用于书写(截断文件,如果文件已存在),'x'用于独家创作,'a'用于追加