Get a file name with tkinter.filedialog.asksaveasfilename to append in it
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).
Use the option confirmoverwrite
to prevent the message, when selecting an existing file.
import tkFileDialog import timeclass Example(): dlg = tkFileDialog.asksaveasfilename(confirmoverwrite=False) fname = dlg if fname != '': try: f = open(fname, "rw+") text = f.read() print text except: f = open(fname, "w") new_text = time.time() f.write(str(new_text)+'\n') f.close()
Edit: Note that I am using f.read()
to be able to print the existing text.
You may want to remove the f.read()
and subsequent print
statement and replace them with a f.seek(0,2)
which positions the pointer at the end of the existing file.
The other option is as follows using the append
option in the file open, which will create the file if it doesn't already exist:
import tkFileDialog import timeclass Example(): dlg = tkFileDialog.asksaveasfilename(confirmoverwrite=False) fname = dlg if fname != '': f = open(fname, "a") new_text = time.time() f.write(str(new_text)+'\n') f.close()