Zac Brown
Zac Brown

Reputation: 6063

Help with filetype association!

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.

Upvotes: 0

Views: 115

Answers (2)

apostrophest
apostrophest

Reputation: 268

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])

Upvotes: 1

Alex Martelli
Alex Martelli

Reputation: 881883

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.

Upvotes: 1

Related Questions