tags:

views:

89

answers:

3

My script.py creates a temporary file in the same dir as the script.

When running it:

python script.py

it works just file

but it doesn't work when you run:

python /path/to/script.py

That's because I'm using a relative path to my temp file in script.py rather than an absolute one. The problem is that I don't know in which path it will be running in, so I need a way to dinamicaly know this.

What about?

os.path.abspath(os.path.dirname(__file__))
A: 

You can use the os.getcwd() method to know the current working directory.

Return a string representing the current working directory. Availability: Unix, Windows.

You can use the os.chdir(path) method to change the current working directory.

Change the current working directory to path. Availability: Unix, Windows.

Desintegr
This answers a completely different question than the one being asked.
Bryan Oakley
+2  A: 

Per the great Dive Into Python:

import sys, os

print 'sys.argv[0] =', sys.argv[0]             1
pathname = os.path.dirname(sys.argv[0])        2
print 'path =', pathname
print 'full path =', os.path.abspath(pathname)
Jonathan Feinberg
What about os.path.abspath(os.path.dirname(\_\_file__)) ?
Juanjo Conti
+2  A: 

The two current answers reflect the ambiguity of your question.

When you've run python /path/to/script.py, where do you want your tempfile? In the current directory (./tempfile.txt) or in /path/to/tempfile.txt?

If the former, you can simply use the relative path (or, for weird and arcane purposes, get the absolute path equivalent to the current directory as @Desintegr suggests, with os.getcwd).

If the latter, you can learn exactly how the script was invoked with sys.argv[0], as @Jonathan suggests, and manipulate that path with the functions in os.path (of course you can also apply those functions to what os.getcwd returns, if the former case applies), or work with os.path.dirname(__file__) and the like (the latter's necessary if you want this latter behavior also when the script is imported as a module, not just when it's run as a main script).

Alex Martelli
Thanks, I want the temp file in the same dir as the script.py
Juanjo Conti
@Juanjo, then `os.path.dirname(__file__)` is probably best and the answer you've selected second-best (as it requires one more `import` -- of `sys` -- which using `__file__` avoids).
Alex Martelli