Python Forum
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
save acts like save as
#1
i am using python(tkinter) to create my text editing software,but my savefile method acts like a saveas method. 
everytime i save it does not overwrite but create a new file instead. 

python code below: 
from tkinter import * 
from tkinter.filedialog import askopenfile 
from tkinter.filedialog import asksaveasfile 



filename = None 

def newfile(): 
global filename 
filename =("Not Set") 

text.delete(0.0,END) 
print(filename) 

def openfile(): 
f=askopenfile(mode='r') 
t=f.read() 
text.delete(0.0,END) 
text.insert(0.0,t) 
print(f) 

def savefile(): 
global filename 
t=text.get(0.0,END) 
f=open(filename,'w') 
f.write(t) 
print(f) 
f.close() 

def saveas(): 
global filename 
f=asksaveasfile(mode='w',defaultextension='.txt')
t=text.get(0.0,END) 
try: 
f.write(t.rstrip()) 
print(f) 
except: 
showerror(title="saveError") 



root=Tk() 
root.title("codiditor")  
root.minsize(width=400,height=400) 
root.maxsize(width=400,height=400)  

text=Text(root,width=400,height=400) 
text.pack() 

menubar=Menu(root) 
filemenu=Menu(menubar) 
filemenu.add_command(label="New texter",command=newfile) 
filemenu.add_command(label="Open texter",command=openfile) 
filemenu.add_command(label="Save texter",command=savefile) 
filemenu.add_command(label="Save as .codime",command=saveascodime) 
filemenu.add_separator() 
filemenu.add_command(label="Say bye",command=root.quit) 
menubar.add_cascade(label="File",menu=f... 

root.config(menu=menubar) 
root.mainloop()

how to make overwrite an existing file(the currently opened file)?
Edit admin:
Learn to use code tag(BBCode help).
Reply
#2
Looks like you code should work... What is the name of the file it saves to, if not the name of the current file? Or do you get the file selection dialog?
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply
#3
(Dec-20-2016, 11:03 AM)Ofnuts Wrote: Looks like you code should work... What is the name of the file it saves to, if not the name of the current file? Or do you get the file selection dialog?
Most part of the text editor works.
But except the save part.
the file selection dialog is for save as file(as shown in the code) ,but the save file should overwrite the existing saved as file.
but the problem is everytime i click save ,it create a new untitled file instead of overwriting it.

Note :I am using Python 3.5.2
Reply
#4
can anyone help,it's already three day ,i did not get my answer yet Sad Big Grin







Reply
#5
When the file dialog comes up do you double click on the file that you want to save to?
That's the way it should work.
If you just click ok, it will save a new default file
Reply
#6
there are two type of save (save and save as )
save as-bring the file dialog to specify the save location.(this works)
save-should just overwrite the existing saved file without confirmation.(this does not work)
i am not having trouble with save as ,i am having problem with save.
Reply
#7
Quote: The tkFileDialog module provides two different pop-up windows you can use to give the user the ability to find existing files or create new files.

.askopenfilename(option=value, ...)

    Intended for cases where the user wants to select an existing file. If the user selects a nonexistent file, a popup will appear informing them that the selected file does not exist.
.asksaveasfilename(option=value, ...)

    Intended for cases where the user wants to create a new file or replace an existing file. If the user selects an existing file, a pop-up will appear informing that the file already exists, and asking if they really want to replace it.

The arguments to both functions are the same:
I use this dialog all the time, have never had an issue with it.

Try this:
try:
    import tk as tk
    import tc as tc
    import tf as tm
except:
    import tkinter as tk
    import tkinter.constants as tc
    import tkinter.filedialog as tf


class tfExample(tk.Frame):
    def __init__(self, root):
        tk.Frame.__init__(self, root)

        # options for buttons
        button_opt = {'fill': tc.BOTH, 'padx': 5, 'pady': 5}

        # define buttons
        tk.Button(self, text='askopenfile', command=self.askopenfile).pack(**button_opt)
        tk.Button(self, text='askopenfilename', command=self.askopenfilename).pack(**button_opt)
        tk.Button(self, text='asksaveasfile', command=self.asksaveasfile).pack(**button_opt)
        tk.Button(self, text='asksaveasfilename', command=self.asksaveasfilename).pack(**button_opt)
        tk.Button(self, text='askdirectory', command=self.askdirectory).pack(**button_opt)

        # define options for opening or saving a file
        self.file_opt = options = {}
        options['defaultextension'] = '.txt'
        options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
        options['initialdir'] = 'C:\\'
        options['initialfile'] = 'myfile.txt'
        options['parent'] = root
        options['title'] = 'This is a title'

        # This is only available on the Macintosh, and only when Navigation Services are installed.
        # options['message'] = 'message'

        # if you use the multiple file version of the module functions this option is set automatically.
        # options['multiple'] = 1

        # defining options for opening a directory
        self.dir_opt = options = {}
        options['initialdir'] = 'C:\\'
        options['mustexist'] = False
        options['parent'] = root
        options['title'] = 'This is a title'

    def askopenfile(self):

        """Returns an opened file in read mode."""

        return tf.askopenfile(mode='r', **self.file_opt)

    def askopenfilename(self):

        """Returns an opened file in read mode.
        This time the dialog just returns a filename and the file is opened by your own code.
        """

        # get filename
        filename = tf.askopenfilename(**self.file_opt)

        # open file on your own
        if filename:
            return open(filename, 'r')

    def asksaveasfile(self):

        """Returns an opened file in write mode."""

        return tf.asksaveasfile(mode='w', **self.file_opt)

    def asksaveasfilename(self):

        """Returns an opened file in write mode.
        This time the dialog just returns a filename and the file is opened by your own code.
        """

        # get filename
        filename = tf.asksaveasfilename(**self.file_opt)

        # open file on your own
        if filename:
            return open(filename, 'w')

    def askdirectory(self):

        """Returns a selected directoryname."""

        return tf.askdirectory(**self.dir_opt)


if __name__ == '__main__':
    root = tk.Tk()
    tfExample(root).pack()
    root.mainloop()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Copy xml content from webpage and save to locally without special characters Nik1811 14 846 Mar-26-2024, 09:28 AM
Last Post: Nik1811
  Open/save file on Android frohr 0 316 Jan-24-2024, 06:28 PM
Last Post: frohr
  save a session in idle akbarza 5 754 Nov-06-2023, 08:36 AM
Last Post: snippsat
  how to save to multiple locations during save cubangt 1 544 Oct-23-2023, 10:16 PM
Last Post: deanhystad
  change directory of save of python files akbarza 3 876 Jul-23-2023, 08:30 AM
Last Post: Gribouillis
  save values permanently in python (perhaps not in a text file)? flash77 8 1,207 Jul-07-2023, 05:44 PM
Last Post: flash77
  does not save in other path than opened files before icode 3 900 Jun-23-2023, 07:25 PM
Last Post: snippsat
  Save image from outlook email cubangt 1 694 Jun-07-2023, 06:52 PM
Last Post: cubangt
  Pymodbus read and save to database stewietopg 3 1,854 Mar-02-2023, 09:32 AM
Last Post: stewietopg
  Save and Close Excel File avd88 0 3,021 Feb-20-2023, 07:19 PM
Last Post: avd88

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020