+ 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?

6th May 2023, 11:49 AM
Yahel
Yahel - avatar
7 ответов
+ 4
Yahel , can you please show your current attempt?
6th May 2023, 1:59 PM
Lothar
Lothar - avatar
6th May 2023, 7:15 PM
Lothar
Lothar - avatar
+ 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
6th May 2023, 5:28 PM
Lothar
Lothar - avatar
+ 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?
6th May 2023, 6:00 PM
Yahel
Yahel - avatar
+ 1
Can you explain why you want that? And can your program take arguments?
6th May 2023, 1:37 PM
Paul
Paul - avatar
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...
6th May 2023, 1:40 PM
Yahel
Yahel - avatar
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.
6th May 2023, 2:04 PM
Yahel
Yahel - avatar