django os.path.dirname(__file__)
Question: I am doing exercises from book:
<http://www.tangowithdjango.com/book17/chapters/templates_static.html>

and I have problem with this code:

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

It shold print dir names. Instead of that it prints first line ( filename) but
2nd and 3rd line are also printed but empty.

I get this behavior with Python 2.7 on Windows 7 and Ubuntu 14.04

EDIT: with this code i get absolute path with `os.path.dirname(__file__)`:

    
    
    import os
    import django
    import settings
    
    print settings.BASE_DIR
    

What is the difference if the same code is imporeted from settings.py and
coded directly?


Answer: The `__file__` value in the _main script_ can be relative to the current
working directory. Use
[`os.path.abspath()`](https://docs.python.org/2/library/os.path.html#os.path.abspath)
to make it absolute first:

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

