1

I am new to the python django framework and I could not quite understand why

os.path.dirname(__file__)

and

os.path.dirname(os.path.dirname(__file__))

return an empty string.

My folder structure is as follows:

djangoWorkspace/
  tangoWithDjangoProject/
     rango/
     tangoWithDjangoProject/
          settings.py

Settings.py contains the code for the dirname.

Tarang Hirani
  • 560
  • 1
  • 12
  • 43

1 Answers1

1

The os.path.dirname(os.path.dirname(__file__)) does not make any sense. You need to call os.path.dirname(os.path.abspath(__file__)) as suggested in the duplicate question.

The result is empty because __file__ contains only the file name of the Python file.

os.path.dirname does not resolve the location of the given file but simply strips away the file name from the given string.

os.path.dirname('../foo/bar/baz.txt')
Out[4]: '../foo/bar'

As you can see the path has not been resolved, the bar.txt has simply been removed from the string.

What you're doing is the equivalent of:

__file__ = 'baz.txt'

os.path.dirname(__file__)
Out[6]: ''

Instead you should do:

os.path.dirname(os.path.abspath(__file__))
Out[10]: '/home/noxdafox/foo/bar'
noxdafox
  • 14,439
  • 4
  • 33
  • 45
  • I was following the tutorial [here](http://www.tangowithdjango.com/book17/chapters/templates_static.html) which has the code I wrote above. And the django library auto generated that code. – Tarang Hirani Jul 19 '15 at 17:10
  • For some reason, using os.path.abspath doesn't work but os.path.dirname works. Not sure why. Can you provide an explanation for that? – Tarang Hirani Jul 19 '15 at 21:59
  • To be clear: all the mentioned methods are not performing a lookup in the FS to find the correct place of the given string. The [os.path.abspath documentation](https://docs.python.org/2/library/os.path.html#os.path.abspath) clearly shows how the function tries to resolve the given path. It's an educated guess and not a reliable search. To better understand what's going on I'd rather print the \__file__ content and the value returned by `os.getcwd`. – noxdafox Jul 20 '15 at 09:48