How can I find script's directory?
You need to call os.path.realpath
on __file__
, so that when __file__
is a filename without the path you still get the dir path:
import os
print(os.path.dirname(os.path.realpath(__file__)))
Find the current directory and file's directory
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
import os
cwd = os.getcwd()
Documentation references for the modules, constants and functions used above:
- The
os
andos.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 pathnamepath
")os.getcwd()
(returns "a string representing the current working directory")os.chdir(path)
("change the current working directory topath
")
What's the best way to determine the location of the current PowerShell script?
PowerShell 3+
# This is an automatic variable set to the current file's/module's directory
$PSScriptRoot
PowerShell 2
Prior to PowerShell 3, there was not a better way than querying theMyInvocation.MyCommand.Definition
property for general scripts. I had the following line at the top of essentially every PowerShell script I had:
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
get script directory name - Python
import os
os.path.basename(os.path.dirname(os.path.realpath(__file__)))
Broken down:
currentFile = __file__ # May be 'my_script', or './my_script' or
# '/home/user/test/my_script.py' depending on exactly how
# the script was run/loaded.
realPath = os.path.realpath(currentFile) # /home/user/test/my_script.py
dirPath = os.path.dirname(realPath) # /home/user/test
dirName = os.path.basename(dirPath) # test
Unix shell script find out which directory the script file resides?
In Bash, you should get what you need like this:
#!/usr/bin/env bash
BASEDIR=$(dirname "$0")
echo "$BASEDIR"
Nicest way to find current directory of file in python
If you're looking to do the same with pathlib
, it could look like this:
from pathlib import Path
package_dir = Path(__file__).parent.absolute()
file_path = package_dir.joinpath("foo.csv")
Unless you're changing current working directory, you may not really need/want to use .absolute()
.
If you actually do not need to know what package_dir
would be, you can also just get the file_path
directly:
file_path = Path(__file__).with_name("foo.csv").absolute()
Which gives you new Path
replacing the file name.
How do I get the directory where a Bash script is located from within the script itself?
#!/usr/bin/env bash
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.
It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:
#!/usr/bin/env bash
SOURCE=${BASH_SOURCE[0]}
while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
SOURCE=$(readlink "$SOURCE")
[[ $SOURCE != /* ]] && SOURCE=$DIR/$SOURCE # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
This last one will work with any combination of aliases, source
, bash -c
, symlinks, etc.
Beware: if you cd
to a different directory before running this snippet, the result may be incorrect!
Also, watch out for $CDPATH
gotchas, and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when calling update_terminal_cwd >&2
on Mac). Adding >/dev/null 2>&1
at the end of your cd
command will take care of both possibilities.
To understand how it works, try running this more verbose form:
#!/usr/bin/env bash
SOURCE=${BASH_SOURCE[0]}
while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET=$(readlink "$SOURCE")
if [[ $TARGET == /* ]]; then
echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
SOURCE=$TARGET
else
DIR=$( dirname "$SOURCE" )
echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
SOURCE=$DIR/$TARGET # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
echo "SOURCE is '$SOURCE'"
RDIR=$( dirname "$SOURCE" )
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
if [ "$DIR" != "$RDIR" ]; then
echo "DIR '$RDIR' resolves to '$DIR'"
fi
echo "DIR is '$DIR'"
And it will print something like:
SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')
SOURCE is './sym2/scriptdir.sh'
DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
Get the path of current script
In RStudio, you can get the path to the file currently shown in the source pane using
rstudioapi::getSourceEditorContext()$path
If you only want the directory, use
dirname(rstudioapi::getSourceEditorContext()$path)
If you want the name of the file that's been run by source(filename)
, that's a little harder. You need to look for the variable srcfile
somewhere back in the stack. How far back depends on how you write things, but it's around 4 steps back: for example,
fi <- tempfile()
writeLines("f()", fi)
f <- function() print(sys.frame(-4)$srcfile)
source(fi)
fi
should print the same thing on the last two lines.
How do I get the path to the current script with Node.js?
I found it after looking through the documentation again. What I was looking for were the __filename
and __dirname
module-level variables.
__filename
is the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/kyle/some/dir/file.js
)__dirname
is the directory name of the current module. (ex:/home/kyle/some/dir
)
Related Topics
How to Explicitly Free Memory in Python
How to Use Glob() to Find Files Recursively
How to Uninstall Python 2.7 on a MAC Os X 10.6.4
How to Sort a Dataframe in Python Pandas by Two or More Columns
What Exactly Is Current Working Directory
When Is "I += X" Different from "I = I + X" in Python
How to Install Pip With Python 3
Text Progress Bar in Terminal With Block Characters
How to Get the Last Element of a List
Urllib and "Ssl: Certificate_Verify_Failed" Error
Why Is "Except: Pass" a Bad Programming Practice
Does Python Have "Private" Variables in Classes
Why Does Integer Division Yield a Float Instead of Another Integer
Delete a Column from a Pandas Dataframe