27

Let's say that I have a python script a.py in /A/B/a.py, and it's in the PATH environment variable. The current working directory is /X/Y/, and it's the directory where I call the /A/B/a.py.

  • In a.py, how to detect /X/Y/? I mean, how to know in which directory the python call is made?
4
  • The directory in which the python call is made is automatically the working directory. Commented Sep 12, 2010 at 19:28
  • No it is not, please copy a script to Windows directory, and run getcwd(), anywhere we get output c:\windows not c:\working_folder Commented Mar 12, 2022 at 1:57
  • @kephalian - I have just tested the following code from a non-admin command prompt in various directories in Windows 11 and it seems to work fine: C:\xxxx > python -c "import os; print(os.getcwd()) Commented Jul 28, 2023 at 21:43
  • Previous comment was because of a configuration in VisualStudio code that caused it to execute in folder of py.exe. Commented Oct 2, 2023 at 4:15

2 Answers 2

37

You can get the current working directory with:

os.getcwd()
Sign up to request clarification or add additional context in comments.

2 Comments

You should use getcwdu() for portability reasons.
The function getcwdu returns a unicode string in Python 2. getcwd in Python 3 returns a unicode string. getcwdb returns a bytestring in Python 3. There is no getcwdu in Python 3.
8
>> os.getcwd()
/X/Y
>> os.path.dirname(os.path.realpath(__file__))   # cannot be called interactively
/A/B
>> sys.path[0]
/A/B
>> os.path.abspath(sys.argv[0])
/A/B/a.py

4 Comments

That gives you the /A/B directory, the location of the a.py.
That's not what he meant, see his question from yesterday (stackoverflow.com/questions/3691921/…).
@Radomir — I thought the directory where the .py file resides is what the OP wanted. Your comment made me reread the OP's question, and see that that is not the case.
If the script is called from path, os.getcwd() returns windows C:\Windows and not path where is executed say C:\Workingfolder

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.