Get a file name with tkinter.filedialog.asksaveasfilename to append in it

Jal picture Jal · Oct 13, 2016 · Viewed 12.3k times · Source

from an GUI application designed with tkinter, I wish to save some datas in a file in appending mode. To get the file's name I use asksaveasfilename from filedialog module. Here is the code:

from tkinter.filedialog import asksaveasfilename

def save_file():

    file_name = asksaveasfilename()

    if file_name:
        f = open(file_name, 'a')
        contents = tab_chrono.text_area.get(1.0, 'end')
        f.write(contents)
        f.close()

The problem happens when I select in the dialog an existing file, I got a warning that the file will be overwritten. It is not true since I append in the file. Is there a way to get rid of this warning ? Or do I have to rewrite a askappendfilename myself ? This is missing in filedialog module. enter image description here

Answer

patthoyts picture patthoyts · Oct 13, 2016

The asksaveasfilename dialog accepts a confirmoverwrite argument to enable or disable the file existence check.

file_name = asksaveasfilename(confirmoverwrite=False)

This can be found in the Tk manual for tk_getSaveFile but doesn't appear to be documented for tkinter. It was introduced in Tk 8.5.11 so is relatively new in Tk terms (released Nov 2011).