2

I have been trying to learn python-unipath and have been getting to grips with basic commands. However, I have been stumped by this issue. So, I would like to get the ancestor(2) of the current file. So, on the python interpretter, I do something like this:

Python 2.7.3 (default, Jan  2 2013, 13:56:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from unipath import Path
>>> ORM_ROOT = Path("/home/foo/lump/foobar/turf/orm/unipath_try.py").ancestor(2)
>>> ORM_ROOT
Path('/home/foo/lump/foobar/turf')

..which is correct and exactly what I want. Now, I wrap this in a file like so:

# -*- coding: utf-8 -*-
# unipath_try.py

from unipath import Path
ORM_ROOT = Path(__file__).ancestor(2)
print ORM_ROOT

when I run this using python unipath_try.py I get no output! No import errors either. I am completely baffled why this is - probably something really stupid. Would appreciate any help/direction on this :(

JohnJ
  • 6,736
  • 13
  • 49
  • 82

2 Answers2

5

Use os.path.abspath(__file__) instead of __file__.

This is because __file__ contains a relative path in your case.

__file__ can contain a relative path or an absolute one in different situations:

So, if you aren't inside the part of sys.path that contains the module, you'll get an absolute path. If you are inside the part of sys.path that contains the module, you'll get a relative path.

If you load a module in the current directory, and the current directory isn't in sys.path, you'll get an absolute path.

If you load a module in the current directory, and the current directory is in sys.path, you'll get a relative path.

(quote from Python __file__ attribute absolute or relative?)

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Thanks a lot for the solution! Accepted your answer now :) – JohnJ Aug 26 '13 at 12:51
  • Just a follow up question: is it better to use `os.path.abspath(__file__)` as default for all cases instead of `__file__`? – JohnJ Aug 26 '13 at 12:54
4

If you run the script in the directory in which the file exists, __file__ is filename.py.

>>> Path('a.py')
Path(u'a.py')
>>> Path('a.py').ancestor(2)
Path(u'')

Pass absolute path using os.path.abspath:

import os

from unipath import Path

ORM_ROOT = Path(os.path.abspath(__file__)).ancestor(2)
print ORM_ROOT

Alternative

You can also use absolute() method.

Path('t.py').absolute().ancestor(2)
falsetru
  • 357,413
  • 63
  • 732
  • 636