0

I am currently using asksaveasfile to save the file, and it is working fine. The only issue I am having is that I cant get the new file name. I know asksaveasfilename exists but if I use them both together they will pop up two windows which I dont want to happen. If I try printing the output of asksaveasfile i get the following:

<_io.TextIOWrapper name='/home/work/newfile.txt' mode='w' encoding='UTF-8'>.

Is there a way I can just get the file name out of this?

Tom Boy
  • 599
  • 2
  • 8
  • 14

1 Answers1

1

Just use the .name attribute of the result of asksaveasfile:

import tkinter
file = tkinter.filedialog.asksaveasfile()
name = file.name

Or you can use asksaveasfilename then open the file yourself:

name = tkinter.filedialog.asksaveasfilename()
file = open(name,'w')

This way you could also use a with statement to ensure the file is closed properly which would be a good idea anyway:

name = tkinter.filedialog.asksaveasfilename()
with open(name,'w') as f:
    NotImplemented #do stuff with the file
Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59
  • This worked, and I used the basename() function to get the filename seperate. But I keep getting my extension in the file name too. For example I get "file.txt" but is there a way I can just get "file"? – Tom Boy Mar 19 '16 at 21:58
  • 1
    either [python how to remove file extension on string](https://www.google.com/webhp?#q=python+how+to+remove+file+extension+on+string) or [How to get the filename without the extension from a path in Python?](http://stackoverflow.com/questions/678236/how-to-get-the-filename-without-the-extension-from-a-path-in-python) – Tadhg McDonald-Jensen Mar 19 '16 at 22:03
  • Yes ... I believe there is an os.path function to separate an extension from the rest, and it is easy to do by finding the last '.'. – Terry Jan Reedy Mar 19 '16 at 22:05
  • 1
    @TerryJanReedy, yes it is called `splitext` and it is posted in the question I linked to. – Tadhg McDonald-Jensen Mar 19 '16 at 22:08