+ 1
Get current working directory (but not exactly) - Python
Assume I have a python script at "~/scripts/main.py" and I'm executing that script from "~/mydir/" by typing "python3 ~/scripts/main.py". I'd like to get from within the python script, main.py, the path "~/mydir/" and not the path of the script "~/scripts/main.py". How can I do that?
7 Antworten
+ 4
Yahel ,
can you please show your current attempt?
+ 4
Yahel ,
see the sample file:
https://code.sololearn.com/c9UBuz8w30P2/?ref=app
+ 3
Yahel ,
maybe this helps?
> i am using windows 10 and the commandline app
> i am now in C:\Program Files\LibreOffice>
> my python script is located in: C:\pystart\test_directory.py
my command line is:
C:\Program Files\LibreOffice> python c:\pystart\test_directory.py
the script test_directory.py uses python pathlib module:
import pathlib
print('running python file: test directory.py')
print(pathlib.Path.cwd())
this outputs:
C:\Program Files\LibreOffice
+ 2
Lothar yes, it helps. It's basically the same as os.getcwd().
That's apparently what I need, but assume I want to get the path of the script within the code, how do I do that?
+ 1
Can you explain why you want that? And can your program take arguments?
0
Paul I want to be able to run this script from everywhere on my pc, and the script creates a file at the directory I'm in while executing the script from its static location.
and it can accept args, but I rather keep it simple...
0
Lothar I have 2 possible solutions which I don't really like:
1. Pass the current working dir to the script execution.
2. Copy the script to the cd.