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?
PS (Don;t know if that matters) On windows I built it a project; while on Ubuntu it's a single .py
file.
Here's a more portable alternative:
self._path = os.path.dirname(os.path.realpath(__file__))
dirname
replaces your loop
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, ie you never went in the if (which is weird since you should at least hit the root at some point)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.