Amarth Gûl
Amarth Gûl

Reputation: 1090

Append Directory on ubuntu using python

I want to get the current file's directory, but by os.path.abspath(__file__), I can only get something like /home/gmarth/Documents/pythonLearning.py, yet I want to remove the file name, left file's path like /home/gmarth/Documents. I achieved this on Windows with the following code:

current = str(os.path.abspath(__file__))
for itera in range(len(current) - 1, 0, -1):
    if current[itera] == '\\':
        dir = current[0: itera]
        break;
self._path = dir

But on ubuntu, nearly the same code doesn't work:

current = str(os.path.abspath(__file__))
for itera in range(len(current)-1, 0, -1):
    if current[itera] == '/':       #only changed here
        directory = current[0: itera]
        break;
self._path = dierctory 

I got:

UnboundLocalError: local variable 'directory' referenced before assignment

That confused me, I don't have much experiences on ubnuntu, how can I get the similar result like Windows?

P.S. (Don;t know if that matters) On windows I built it a project; while on Ubuntu it's a single .py file.

Upvotes: 0

Views: 36

Answers (2)

anthony sottile
anthony sottile

Reputation: 70145

Here's a more portable alternative:

self._path = os.path.dirname(os.path.realpath(__file__))

dirname replaces your loop

Upvotes: 2

hogo
hogo

Reputation: 11

Your code works fine on my ubuntu. (minus the typo at the end)

The error mean that you never used a variable named "directory" before trying to put it in _path, i.e. you never went in the if (which is weird since you should at least hit the root at some point)

Upvotes: 0

Related Questions