Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: script's directory

I was looking for a solution, but have not found what I need.

Script path: /dir/to/script/script.py or C:\dir\script.py

Excepted result:

$ ./script.py
output: /dir/to/script
$ cd .. && ./script/script.py
output: /dir/to/script

Is there any function in os module or something?


I mixed solutions and write:

print os.path.abspath(os.path.dirname(__file__))

But it's ugly. Is there better way?

like image 825
Mateusz Jagiełło Avatar asked Sep 03 '11 14:09

Mateusz Jagiełło


People also ask

Where is the Python scripts directory?

getcwd() method to get Python Script location. The os. getcwd() method is used for getting the Current Working Directory in Python. The absolute path to the current working directory is returned in a string by this function of the Python OS module.

How do I print the current directory in Python?

Get the current working directory: os. getcwd stands for "get current working directory", and the Unix command pwd stands for "print working directory". Of course, you can print the current working directory with os. getcwd() and print() .

Where are my Python files saved?

Writing Your First Python Program Create a folder called PythonPrograms on your C:\ drive. You will be storing all your Python programs in this folder. Go to Start and either type Run in the Start Search box at the bootom or click on Run.


1 Answers

os.path.realpath will give you the result:

os.path.dirname(os.path.realpath(__file__))
like image 167
Mu Qiao Avatar answered Sep 23 '22 01:09

Mu Qiao