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
")
How do I get the full path of the current file's directory?
The special variable __file__
contains the path to the current file. From that we can get the directory using either pathlib
or the os.path
module.
Python 3
For the directory of the script being run:
import pathlib
pathlib.Path(__file__).parent.resolve()
For the current working directory:
import pathlib
pathlib.Path().resolve()
Python 2 and 3
For the directory of the script being run:
import os
os.path.dirname(os.path.abspath(__file__))
If you mean the current working directory:
import os
os.path.abspath(os.getcwd())
Note that before and after file
is two underscores, not just one.
Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__
may not be set since there is no notion of "current file". The above answer assumes the most common scenario of running a python script that is in a file.
References
- pathlib in the python documentation.
- os.path - Python 2.7, os.path - Python 3
- os.getcwd - Python 2.7, os.getcwd - Python 3
- what does the __file__ variable mean/do?
How to get the current working directory using python 3?
It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.
To change current working dir to the one containing your script you can use:
import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())
The __file__
variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?
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.
List files ONLY in the current directory
Just use os.listdir
and os.path.isfile
instead of os.walk
.
Example:
import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
# do something
But be careful while applying this to other directory, like
files = [f for f in os.listdir(somedir) if os.path.isfile(f)]
which would not work because f
is not a full path but relative to the current directory.
Therefore, for filtering on another directory, do os.path.isfile(os.path.join(somedir, f))
(Thanks Causality for the hint)
Get folder name of the file in Python
You can use dirname
:
os.path.dirname(path)
Return the directory name of pathname path. This is the first element
of the pair returned by passing path to the function split().
And given the full path, then you can split normally to get the last portion of the path. For example, by using basename
:
os.path.basename(path)
Return the base name of pathname path. This is the second element of
the pair returned by passing path to the function split(). Note that
the result of this function is different from the Unix basename
program; where basename for '/foo/bar/' returns 'bar', the basename()
function returns an empty string ('').
All together:
>>> import os
>>> path=os.path.dirname("C:/folder1/folder2/filename.xml")
>>> path
'C:/folder1/folder2'
>>> os.path.basename(path)
'folder2'
What is the current directory in a batch file?
From within your batch file:
%cd%
refers to the current working directory (variable)%~dp0
refers to the full path to the batch file's directory (static)%~dpnx0
and%~f0
both refer to the full path to the batch directory and file name (static).
See also: What does %~dp0 mean, and how does it work?
how can i get the current file directory in R
Basically, if you write scripts and those scripts depend on where they are, then you are Doing It Wrong.
Write code in packages. Parameterise functions to make them generally applicable. If you have folders with data in, then make one of those parameters a folder.
A script called with source()
cannot reliably locate itself, but that shouldn't be a problem, because WHATEVER CALLED THE SCRIPT knows where the script is (it has to, or how else can it call it?) so it could pass that as a parameter. Something like:
> youarehere = "C:\foo\"
> source("C:\foo\bar.R")
and now bar.R
can do setwd(youarehere)
and it will work, even if it is badly written such that it relies on sourcing other code in its containing folder.
Or you can do:
> setwd(youarehere)
> source("bar.R")
in your calling function.
But really, its a fail, its a sign of badly written code. Use functions, write packages, use devtools, its really not that hard, then your code will work anywhere and you wont be writing stupid scripts that are a twisty turny maze of source()
calls.
Stay classy.
Related Topics
Why Is _Init_() Always Called After _New_()
What's the Difference Between Eval, Exec, and Compile
How to Print a Single Backslash
In Python, How to Determine If an Object Is Iterable
Explanation of How Nested List Comprehension Works
How to Check Which Version of Python Is Running My Script
Taking Subarrays from Numpy Array With Given Stride/Stepsize
Difference Between Null=True and Blank=True in Django
How to Fix "Attempted Relative Import in Non-Package" Even With _Init_.Py
Combine Two Columns of Text in Pandas Dataframe
Sort a List by Multiple Attributes
Using Global Variables Between Files