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
")
Get current folder path
You should not use Directory.GetCurrentDirectory()
in your case, as the current directory may differ from the execution folder, especially when you execute the program through a shortcut.
It's better to use Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
for your purpose. This returns the pathname where the currently executing assembly resides.
While my suggested approach allows you to differentiate between the executing assembly, the entry assembly or any other loaded assembly, as Soner Gönül said in his answer,
System.IO.Path.GetDirectoryName(Application.ExecutablePath);
may also be sufficient. This would be equal to
System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
Windows shell command to get the full path to the current directory?
Use cd
with no arguments if you're using the shell directly, or %cd%
if you want to use it in a batch file (it behaves like an environment variable).
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 show current directory in ipython prompt
Assuming you're interested in configuring this for all subsequent invocations of ipython, run the following (in a traditional shell, like bash :) ). It appends to your default ipython configuration, creating it if necessary. The last line of the configuration file will also automatically make all the executables in your $PATH available to simply run in python, which you probably also want if you're asking about cwd in the prompt. So you can run them without a ! prefix. Tested with IPython 7.18.1.
mkdir -p ~/.ipython/profile_default
cat >> ~/.ipython/profile_default/ipython_config.py <<EOF
from IPython.terminal.prompts import Prompts, Token
import os
class MyPrompt(Prompts):
def cwd(self):
cwd = os.getcwd()
if cwd.startswith(os.environ['HOME']):
cwd = cwd.replace(os.environ['HOME'], '~')
cwd_list = cwd.split('/')
for i,v in enumerate(cwd_list):
if i not in (1,len(cwd_list)-1): #not last and first after ~
cwd_list[i] = cwd_list[i][0] #abbreviate
cwd = '/'.join(cwd_list)
return cwd
def in_prompt_tokens(self, cli=None):
return [
(Token.Prompt, 'In ['),
(Token.PromptNum, str(self.shell.execution_count)),
(Token.Prompt, '] '),
(Token, self.cwd()),
(Token.Prompt, ': ')]
c.TerminalInteractiveShell.prompts_class = MyPrompt
c.InteractiveShellApp.exec_lines = ['%rehashx']
EOF
(c.PromptManager only works in older versions of ipython.)
How to get Current Directory?
I would recommend reading a book on C++ before you go any further, as it would be helpful to get a firmer footing. Accelerated C++ by Koenig and Moo is excellent.
To get the executable path use GetModuleFileName:
TCHAR buffer[MAX_PATH] = { 0 };
GetModuleFileName( NULL, buffer, MAX_PATH );
Here's a C++ function that gets the directory without the file name:
#include <windows.h>
#include <string>
#include <iostream>
std::wstring ExePath() {
TCHAR buffer[MAX_PATH] = { 0 };
GetModuleFileName( NULL, buffer, MAX_PATH );
std::wstring::size_type pos = std::wstring(buffer).find_last_of(L"\\/");
return std::wstring(buffer).substr(0, pos);
}
int main() {
std::cout << "my directory is " << ExePath() << "\n";
}
How to get current working directory path c#?
You can use static Directory
class - however current directory is distinct from the original directory, which is the one from which the process was started.
System.IO.Directory.GetCurrentDirectory();
So you can use the following to get the directory path of the application executable:
System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
Related Topics
Why Can't We Declare Object of a Class Inside the Same Class
Equivalent of "Using Namespace X" for Scoped Enumerations
Conversion from Int** to Const Int**
How to Force Inclusion of "Unused" Object Definitions in a Library
How to Use Unicode Range in C++ Regex
Different Compiler Behavior for Expression: Auto P {Make_Pointer()};
Are the "Usual Arithmetic Conversions" and the "Integer Promotions" the Same Thing
Why am I Able to Make a Function Call Using an Invalid Class Pointer
Differencebetween "::" "." and "->" in C++
Adding Signals/Slots (Qobject) to Qgraphicsitem: Performance Hit
Erasing Vector::End from Vector
Does Reinterpret_Cast Lead to Undefined Behavior
How to Convert from Lpctstr to Std::String
Apply Function to All Eigen Matrix Element
Writing a Matrix into a Single Txt File with Mpi