1

I am calling a python 3.10 file from the Anaconda command line (windows, in a conda environment) and noticed that when os.getcwd() is called within a script via command line, it outputs the root directory (I think this is the correct terminology) rather than the directory of the file from which it is called.

So if I run python C:/Users/u03132tk/Python/MyTool/Script.py on command line, I print C:/Users/u03132tk rather than C:/Users/u03132tk/Python/MyTool.

Is there any way to force the path to derive from the script?

Cheers, Tim

C:/Users/u03132tk/Python/MyTool/Script.py

import os
print (os.getcwd())
asked Jan 29, 2024 at 18:30

1 Answer 1

1

When you run a Python script from the command line, os.getcwd() returns the current working directory, which may not necessarily be the directory of the script. The above happens especially when you have different folders in your app root directory

To get the directory of the script itself, you can use os.path.dirname(os.path.abspath(__file__)) within your script. This will give you the absolute path of the directory containing the script.

answered Jan 29, 2024 at 18:37
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.