views:

28

answers:

2

I have the actual association part down, but when I open the file that is associated with my Python program, how do I get the filepath of the file opened?

I think it is something like sys.argv? But that just returns the path to the python program, not the associated file.

+1  A: 

The __file__ attribute of your module looks what you're looking for. E.g., save in foo.py:

$ cat foo.py
print 'Hello', __file__
$ python foo.py 
Hello foo.py

os.path.abspath will help you if you want the absolute rather than relative path, etc, etc.

Alex Martelli
Huh? I need the pathanme of the file I double clicked to open the program i.e. I double click file1.dgf and it opens prog.exe. How do I get the full path to file1.dfg?
Zachary Brown
You tagged your question as `python`, so what's `prog.exe` got to do with it? Anyway, I suspect your question is strongly OS-dependent, and since you have no OS-related tags, I don't know whether the "association" is in Windows, MacOSX, KDE, Gnome, or what else. Isn't your (python?) program getting the clicked file's path as `sys.argv[1]`? It should, in these environments, but since I don't know your environment, it's hard to guess!-)
Alex Martelli
It is a Windows platform. Prog.exe is the Python program compiled to .exe, thus filetype association. It is only getting the path of itself when I use sys.argv[1], I'm not sure why.
Zachary Brown
+1  A: 

The contents of sys.argv are platform-dependent, as noted in sys.argv. I do know that sys.argv[0] is the full path on Windows only when you open .py files using the shell by double-clicking on it. Using the command line just results in the script name.

The os module provides platform-independent solutions. The full path to your script should always be available with the following code:

import os.path
import sys

print os.path.abspath(sys.argv[0])