无法从Python写入文本文件

2024-09-27 21:27:20 发布

您现在位置:Python中文网/ 问答频道 /正文

这可能很简单,但我仍然不知道解决办法是什么。我有这个代码,这是一个较长代码的样本。在

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")

slotchoosedoctor,和{}来自用户通过单击单选按钮和复选按钮输入的信息。我试图向slotchoosedoctorspecialchoose添加一个字符串值,然后将其保存到一个文本文件中。但问题是每次我运行它,打开文本文件test2.txt,它只会有specialistchoose值。在


Tags: txtgetifaswithopenamfile
1条回答
网友
1楼 · 发布于 2024-09-27 21:27:20

{{cd2>你每一次都在重写文件。如果您想累积多次写入文件的文本,则需要使用append模式(a)。在

Python 2文档:

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

Python 3文档:

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

mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for exclusive creation and 'a' for appending

相关问题 更多 >

    热门问题