Python get main file path

Find path to currently running file [duplicate]

How can I find the full path to the currently running Python script? That is to say, what do I have to do to achieve this:

$ pwd /tmp $ python baz.py running from /tmp file is baz.py 

8 Answers 8

__file__ is NOT what you are looking for. Don’t use accidental side-effects

sys.argv[0] is always the path to the script (if in fact a script has been invoked) — see http://docs.python.org/library/sys.html#sys.argv

__file__ is the path of the currently executing file (script or module). This is accidentally the same as the script if it is accessed from the script! If you want to put useful things like locating resource files relative to the script location into a library, then you must use sys.argv[0] .

C:\junk\so>type \junk\so\scriptpath\script1.py import sys, os print "script: sys.argv[0] is", repr(sys.argv[0]) print "script: __file__ is", repr(__file__) print "script: cwd is", repr(os.getcwd()) import whereutils whereutils.show_where() C:\junk\so>type \python26\lib\site-packages\whereutils.py import sys, os def show_where(): print "show_where: sys.argv[0] is", repr(sys.argv[0]) print "show_where: __file__ is", repr(__file__) print "show_where: cwd is", repr(os.getcwd()) C:\junk\so>\python26\python scriptpath\script1.py script: sys.argv[0] is 'scriptpath\\script1.py' script: __file__ is 'scriptpath\\script1.py' script: cwd is 'C:\\junk\\so' show_where: sys.argv[0] is 'scriptpath\\script1.py' show_where: __file__ is 'C:\\python26\\lib\\site-packages\\whereutils.pyc' show_where: cwd is 'C:\\junk\\so' 

Источник

Find the current directory and file’s directory [duplicate]

This question is blatantly two questions in one and should have been closed as needing more focus. Both questions are simple reference questions, and thus ought to each have separate canonicals that this can be dupe-hammered with. However, I have been absolutely tearing my hair out trying to find a proper canonical for only the first question. I am turning up countless duplicates for the second question, most of which involve OP not realizing there is a difference.

Читайте также:  Javascript оператор деления с остатком

I have added the best I could find for «Q. How do I determine the current directory? A. Use os.getcwd() » after literally hours of searching. Ugh.

13 Answers 13

To get the full path to the directory a Python file is contained in, write this in that file:

import os dir_path = os.path.dirname(os.path.realpath(__file__)) 

(Note that the incantation above won’t work if you’ve already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir() call.)

To get the current working directory use

Documentation references for the modules, constants and functions used above:

  • The os and os.path modules.
  • The __file__ constant
  • os.path.realpath(path) (returns «the canonical path of the specified filename, eliminating any symbolic links encountered in the path»)
  • os.path.dirname(path) (returns «the directory name of pathname path «)
  • os.getcwd() (returns «a string representing the current working directory»)
  • os.chdir(path) («change the current working directory to path «)

file will not work if invoked from an IDE (say IDLE). Suggest os.path.realpath(‘./’) or os.getcwd(). Best anser in here: stackoverflow.com/questions/2632199/…

@Neon22 might suit some needs, but I feel it should be noted that those things aren’t the same at all — files can be outside the working directory.

@Moberg Often the paths will be the same when reversing realpath with dirname , but it will differ when the file (or its directory) is actually a symbolic link.

And the __file__ attribute can help you find out where the file you are executing is located. This Stack Overflow post explains everything: How do I get the path of the current executed file in Python?

You may find this useful as a reference:

import os print("Path at terminal when executing this file") print(os.getcwd() + "\n") print("This file path, relative to os.getcwd()") print(__file__ + "\n") print("This file full path (following symlinks)") full_path = os.path.realpath(__file__) print(full_path + "\n") print("This file directory and name") path, filename = os.path.split(full_path) print(path + ' --> ' + filename + "\n") print("This file directory only") print(os.path.dirname(full_path)) 

The __file__ is an attribute of the module object. You need run the code inside a Python file, not on the REPL.

pwd /home/skovorodkin/stack tree . └── scripts ├── 1.py └── 2.py 

In order to get the current working directory, use Path.cwd() :

from pathlib import Path print(Path.cwd()) # /home/skovorodkin/stack 

To get an absolute path to your script file, use the Path.resolve() method:

print(Path(__file__).resolve()) # /home/skovorodkin/stack/scripts/1.py 

And to get the path of a directory where your script is located, access .parent (it is recommended to call .resolve() before .parent ):

print(Path(__file__).resolve().parent) # /home/skovorodkin/stack/scripts 

Please note, that Path.cwd() , Path.resolve() and other Path methods return path objects ( PosixPath in my case), not strings. In Python 3.4 and 3.5 that caused some pain, because open built-in function could only work with string or bytes objects, and did not support Path objects, so you had to convert Path objects to strings or use the Path.open() method, but the latter option required you to change old code:

File scripts/2.py

from pathlib import Path p = Path(__file__).resolve() with p.open() as f: pass with open(str(p)) as f: pass with open(p) as f: pass print('OK') 

Output

python3.5 scripts/2.py Traceback (most recent call last): File "scripts/2.py", line 11, in with open(p) as f: TypeError: invalid file: PosixPath('/home/skovorodkin/stack/scripts/2.py') 

As you can see, open(p) does not work with Python 3.5.

PEP 519 — Adding a file system path protocol, implemented in Python 3.6, adds support of PathLike objects to the open function, so now you can pass Path objects to the open function directly:

Источник

How do I get the path of the Python script I am running in? [duplicate]

How do I get the path of a the Python script I am running in? I was doing dirname(sys.argv[0]) , however on Mac I only get the filename — not the full path as I do on Windows. No matter where my application is launched from, I want to open files that are relative to my script file(s).

@sorin oh, but they are; a module object can be created for any script file. Just because something never actually gets import ed doesn’t make it «not a module». The answer is the same, anyway: treat the script as a module (use some kind of bootstrap if really necessary) and then apply the same technique.

Yes, a script is a module, but this well-asked question should be re-opened. It has not been answered here, and the «duplicate» question is not a duplicate because it only answers how to get the location of a module you have loaded, not the one you are in.

@acidzombie24 you don’t need the full path to open and manipulate files from your directory. you can, for example, open(‘images/pets/dog.png’) and Python will do the other.

5 Answers 5

Use this to get the path of the current file. It will resolve any symlinks in the path.

import os file_path = os.path.realpath(__file__) 

This works fine on my mac. It won’t work from the Python interpreter (you need to be executing a Python file).

import os print os.path.abspath(__file__) 

Thanks. This get the path of the .py file where the code is written, which is what I want, even though OP wanted another path.

This should be combined with information in the other answer: os.path.abspath(os.path.dirname(__file__)) will give the directory.

import sys, os print('sys.argv[0] =', sys.argv[0]) pathname = os.path.dirname(sys.argv[0]) print('path =', pathname) print('full path =', os.path.abspath(pathname)) 

I like how your answer shows a lot of different variations and features from python to solve the question.

@SorinSbarnea see the subject of the question: get the path of the running script (the script which has been executed). An import ed module is just a resource.

The question is not very clear, but your solution would work only if it is called at the beginning of the script (in order to be sure that nobody changes the current directory). I am inclined to use the inspect method instead. «running script» is not necessarily same as «called script» (entry point) or «currently running script».

The accepted solution for this will not work if you are planning to compile your scripts using py2exe. If you’re planning to do so, this is the functional equivalent:

Py2exe does not provide an __file__ variable. For reference: http://www.py2exe.org/index.cgi/Py2exeEnvironment

Unluckily this does not work on Mac, as the OP says. Please see sys.argv: it is operating system dependent whether this is a full pathname or not

@Stefano that’s not a problem. To make sure it’s an absolute (full) pathname, use os.path.abspath(. )

If you have even the relative pathname (in this case it appears to be ./ ) you can open files relative to your script file(s). I use Perl, but the same general solution can apply: I split the directory into an array of folders, then pop off the last element (the script), then push (or for you, append ) on whatever I want, and then join them together again, and BAM! I have a working pathname that points to exactly where I expect it to point, relative or absolute.

Of course, there are better solutions, as posted. I just kind of like mine.

In python this does not work if you call the script from a completely different path, e.g. if you are in ~ and your script is in /some-path/script you’ll get ./ equal to ~ and not /some-path as he asked (and I need too)

Источник

Оцените статью