Python how to keep writing to a file without erasing what's already there

孤街浪徒 提交于 2019-12-20 03:05:37

问题


Writing my python 3.3 program in Windows, I've run into a little problem. I'm trying to write some lines of instructions to a file for the program to execute. But every time I file.write() the next line, it replaces the previous line. I want to be able to keep writing as many lines to this file as possible. NOTE: Using "\n" doesn't seem to work because you don't know how many lines there are going to be. Please help! Here is my code (being a loop, I do run this multiple times):

menu = 0
while menu != None:
    menu = lipgui.choicebox("Select an option:", choices=["choice1", "choice2", "choice3"])
    file = open("file.txt", "w")
    if menu == "choice1":
       text_to_write = lipgui.enterbox("Text to write:")
       file.write(text_to_write)

回答1:


Every time you open a file for writing it is erased (truncated). Open the file for appending instead, or open the file just once and keep it open.

To open a file for appending, use a instead of w for the mode:

while menu != None:
    menu = lipgui.choicebox("Select an option:", choices=["choice1", "choice2", "choice3"])
    file = open("file.txt", "a")
    if menu == "choice1":
       text_to_write = lipgui.enterbox("Text to write:")
       file.write(text_to_write)

or open the file outside the loop:

file = open("file.txt", "w")

while menu != None:
    menu = lipgui.choicebox("Select an option:", choices=["choice1", "choice2", "choice3"])
    if menu == "choice1":
       text_to_write = lipgui.enterbox("Text to write:")
       file.write(text_to_write)

or just once the first time you need it:

file = None

while menu != None:
    menu = lipgui.choicebox("Select an option:", choices=["choice1", "choice2", "choice3"])
    if file is None:
        file = open("file.txt", "w")
    if menu == "choice1":
       text_to_write = lipgui.enterbox("Text to write:")
       file.write(text_to_write)


来源:https://stackoverflow.com/questions/25553031/python-how-to-keep-writing-to-a-file-without-erasing-whats-already-there

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!