-1

So I am trying to open a file using tkinter dialogue. I want the location of the file selected. Is there any way I can get it? This is my code:

from tkinter.filedialog import asksaveasfile, askopenfile

root =tk.Tk()
files = [('All Files', '*.*'), ('Python Files', '*.py'), ('Text Document', '*.txt')]
file = askopenfile(mode ='r', filetypes = files, defaultextension = files)

  • Does this answer your question? [Get path from open file in Python](https://stackoverflow.com/questions/9542435/get-path-from-open-file-in-python) – Ruzihm Jun 26 '20 at 22:21
  • Actually No. Because in that question, he is providing path before somewhere in the code however what I'm trying to achieve is, I want path for any file that will be opened by the user. I tried using method f.name using the same question method however my python got crashed instead. – Mavis_Ackerman Jun 26 '20 at 22:25
  • 1
    so `import os` `file = askopenfile(mode ='r', filetypes = files, defaultextension = files)` `fileName = os.path.realpath(file.name)` doesn't work for you? That is taken almost verbatim from that page... – Ruzihm Jun 26 '20 at 22:27
  • 2
    You claimed yo utried using `f.name` (though it should have been `file.name`) and python crashed. What was the error message? – Bryan Oakley Jun 26 '20 at 22:37

1 Answers1

0

"If the user selects a file, the returned value is the complete path name of the selected file. If the user uses the Cancel button, the function returns an empty string."

Quoted from here: https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/tkFileDialog.html

Paul Cornelius
  • 9,245
  • 1
  • 15
  • 24
  • 1
    So you are suggesting use `tkinter.filedialog.askopenfilename` - might want to include that relevant bit in the answer itself. – Ruzihm Jun 26 '20 at 22:31