0

I am working on creating a python Tk program and found that saving files is annoying. I have an open button and a save button. For example I call

file = tkFileDialog.askopenfile(mode='rb',title='Select a file')

from this function

def open_command(self):

In another function

def save_file(self):

I want to save the file. To save the file under the same name I have to call

file = tkFileDialog.asksaveasfile(mode='w')

again and this opens another window, then it asks you to name the file, and finaly prompts you if you want to overwrite the file. Is there a way to save the file without any windows? Is it possible in any way to not close the file in one function and then write to the file and save it in another function?

1
  • Do you mean a silent save/overwrite? Commented Sep 2, 2015 at 20:48

1 Answer 1

1

It sounds like you want a silent save/overwrite, so that a user can open a file, modify it, and then hit Save to update the saved file. I would recommend asking for a file name, as askopenfile asks for the name and then immediately gives you the file object by that name.

self.save_name = tkFileDialog.askopenfilename(title='Select a file')
with open(self.save_name, 'rb') as f:
    self.the_data = f.read() # insert processing here

If you ask for just the name, you can save that name and then later use it directly in your save function:

with open(self.save_name, 'wb') as output:
    output.write(self.the_data) # insert processing here
Sign up to request clarification or add additional context in comments.

2 Comments

This helps, but can I only open a file once and then save it after some changes without having to select the file and open another window.(just click 'save' and its done)
Are you properly saving a reference to the file name you got in open_command? The save_file function should simply refer to that saved name. It should be able to do so as many times as needed. Is that reference being deleted somewhere?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.