-3
import tkinter as tk
from tkinter.filedialog import askopenfilename
root = tk.Tk()
# show askopenfilename dialog without the Tkinter window
root.withdraw()
# default is all file types
file_name = askopenfilename()
print(file_name)

this is the code i am trying to use in python that allows me to select a file and return whichever file i select. the program allows me to select a file but rather than open the document it shows the files path in the Python shell. how can i fix this? thanks

Chris Gilroy
  • 15
  • 1
  • 5
  • What do you mean by "open the document"? That generally means running a program that does something with documents, like a word processor or a graphics editor. What kind of files are they? – Lee Daniel Crocker Apr 23 '13 at 14:24
  • i am basically looking to open a document as if you were going to double click it locally. it doesnt need to be parsed. i am creating this GUI to give the user an option of opening a selection of webpages so all i want to do is simply open the file they select – Chris Gilroy Apr 23 '13 at 14:38
  • Yeah, I thought that's what you meant. That's a very system-dependent thing. [this](http://stackoverflow.com/questions/434597/open-document-with-default-application-in-python) should help. – Lee Daniel Crocker Apr 23 '13 at 14:45

2 Answers2

2

askopenfilename returns the path to the file. The next step is just open it and read its content:

file_name = askopenfilename()
with open(file_name) as f:
    print(f.read())

Remember that this method returns '' if you close the dialog, so you have to call open only if the filename is not the empty string.

A. Rodas
  • 20,171
  • 8
  • 62
  • 72
  • thats very close, but rather than display the information in the shell i am looking to simply open the document as if i was to double click it. for example, i have created webpages and i am trying to open these pages in a web browser through the prompt above – Chris Gilroy Apr 23 '13 at 14:34
  • @ChrisGilroy In that case, use `os.system('open ' + filename)` (`os.system('start ' + filename)` on Windows) to open it with the default application. – A. Rodas Apr 23 '13 at 14:44
0

If you are on a PC:

    import os
    os.startfile(file_name)

This will open the file with the default program for opening that file type in the computer.

If you are on OSX, then I believe it's:

    import subprocess
    path_to_file = 'path/to/file'
    path_to_program = r'C:\path\to\program.exe'
    subprocess.Popen("%s %s" % (path_to_program, path_to_file))
hillmandj
  • 83
  • 2
  • 11