Luke Dinkler
Luke Dinkler

Reputation: 769

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

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)

Upvotes: 3

Views: 11094

Answers (2)

SWAPNIL PATIL
SWAPNIL PATIL

Reputation: 15

In order to solve this kind of problem and work on all applications including real time applications, you have to first open a file in append mode outside loop and open the same file in write mode inside the loop.

Here is the example in different context(Removing duplicates in real time).

import sched, time
s = sched.scheduler(time.time, time.sleep)
outfile = open('D:/RemoveDup.txt', "a")
def do_something(sc):  #loop  
    outfile = open('D:/RemoveDup.txt', "w")
    #do your stuff........    
    infile = open('D:/test.txt', "r")
    lines_seen = set()
    for line in infile:
        if line not in lines_seen:
            outfile.write(line)
            lines_seen.add(line)
    s.enter(10, 1, do_something, (sc,))
    s.enter(10, 1, do_something, (s,))
s.run()

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121514

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)

Upvotes: 8

Related Questions