- Find the current directory and file’s directory [duplicate]
- 13 Answers 13
- File scripts/2.py
- Output
- Python Get Current Directory – Print Working Directory PWD Equivalent
- How to Get The Current Directory Using the os.getcwd() Method in Python
- How to Get The Current Directory Using the Path.cwd() Method in Python
- Conclusion
- How do I get the path of the Python script I am running in? [duplicate]
- 5 Answers 5
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.
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:
Python Get Current Directory – Print Working Directory PWD Equivalent
Dionysia Lemonaki
In this article, you will learn how to get the current working directory (another name for folder) in Python, which is the equivalent of using the pwd command.
There are a couple of ways to get the current working directory in Python:
- By using the os module and the os.getcwd() method.
- By using the pathlib module and the Path.cwd() method.
How to Get The Current Directory Using the os.getcwd() Method in Python
The os module, which is part of the standard Python library (also known as stdlib), allows you to access and interact with your operating system.
To use the os module in your project, you need to include the following line at the top of your Python file:
Once you have imported the os module, you have access to the os.getcwd() method, which allows you to get the full path of the current working directory.
Let’s look at the following example:
import os # get the current working directory current_working_directory = os.getcwd() # print output to the console print(current_working_directory) # output will look something similar to this on a macOS system # /Users/dionysialemonaki/Documents/my-projects/python-project
The output is a string that contains the absolute path to the current working directory – in this case, python-project .
To check the data type of the output, use the type() function like so:
print(type(current_working_directory)) # output #
Note that the current working directory doesn’t have a trailing forward slash, / .
Keep in mind also that output will vary depending on the directory you are running the Python script from as well as your Operating System.
How to Get The Current Directory Using the Path.cwd() Method in Python
In the previous section, you saw how to use the os module to get the current working directory. However, you can use the pathlib module to achieve the same result.
The pathlib module was introduced in the standard library in Python’s 3.4 version and offers an object-oriented way to work with filesystem paths and handle files.
To use the pathlib module, you first need to import it at the top of your Python file:
Once you have imported the pathlib module, you can use the Path.cwd() class method, which allows you to get the current working directory.
Let’s look at the following example:
from pathlib import Path # get the current working directory current_working_directory = Path.cwd() # print output to the console print(current_working_directory) # output will look something similar to this on a macOS system # /Users/dionysialemonaki/Documents/my-projects/python-project
As you can see, the output is the same as the output I got when I used the os.getcwd() method. The only difference is the data type of the output:
print(type(current_working_directory)) # output #
Conclusion
And there you have it! You now know how to get the full path to the current directory in Python using both the os and pathlib modules.
Thanks for reading, and happy coding!
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)