Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find script's directory? [duplicate]

Consider the following Python code:

import os print os.getcwd() 

I use os.getcwd() to get the script file's directory location. When I run the script from the command line it gives me the correct path whereas when I run it from a script run by code in a Django view it prints /.

How can I get the path to the script from within a script run by a Django view?

UPDATE:
Summing up the answers thus far - os.getcwd() and os.path.abspath() both give the current working directory which may or may not be the directory where the script resides. In my web host setup __file__ gives only the filename without the path.

Isn't there any way in Python to (always) be able to receive the path in which the script resides?

like image 693
Jonathan Livni Avatar asked Feb 08 '11 15:02

Jonathan Livni


People also ask

Can TreeSize find duplicate files?

TreeSize is a must-have for neatly organizing projects and a lifesaver for overfilled hard drives. TreeSize Duplicate Search can detect duplicate files in a quick and easy way, both on servers and on local drives. This allows you to resolve file duplicates without having to worry about losing important content.

How do I find duplicate files on my hard drive?

Download, install and launch Duplicate Sweeper. Click "Add Folder" and select the folders on your external hard drive that you wish to search for duplicates. Once all the required folders have been added, click "Start Duplicate Search" to begin the search.

Is there a duplicate file finder?

#1) XYplorerXYplorer is a duplicate file finder that allows users to search for duplicate files on the system and manage other files efficiently. This application has a duplicate detection feature that will enable them to create a deep search and locate duplicate files on the system.


1 Answers

You need to call os.path.realpath on __file__, so that when __file__ is a filename without the path you still get the dir path:

import os print(os.path.dirname(os.path.realpath(__file__))) 
like image 143
Czarek Tomczak Avatar answered Sep 24 '22 17:09

Czarek Tomczak