使用python在ubuntu上追加目录
我想获取当前文件的目录,但通过使用python在ubuntu上追加目录,python,ubuntu,directory,Python,Ubuntu,Directory,我想获取当前文件的目录,但通过os.path.abspath(uuu file_uuu),我只能获取类似/home/gmarth/Documents/pythonLearning.py,但我想删除文件名,留下文件路径,如/home/gmarth/Documents。我在Windows上通过以下代码实现了这一点: current = str(os.path.abspath(__file__)) for itera in range(len(current) - 1, 0, -1): if
os.path.abspath(uuu file_uuu)
,我只能获取类似/home/gmarth/Documents/pythonLearning.py
,但我想删除文件名,留下文件路径,如/home/gmarth/Documents
。我在Windows上通过以下代码实现了这一点:
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
但在ubuntu上,几乎相同的代码不起作用:
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
我得到:
UnboundLocalError: local variable 'directory' referenced before assignment
这让我很困惑,我在ubnuntu上没有太多经验,我怎么能像Windows一样得到类似的结果呢
另外(不知道这是否重要)在windows上,我把它建成了一个项目;在Ubuntu上,它是一个
.py
文件。您的代码在我的Ubuntu上运行良好。(减去末尾的打字错误)
这个错误意味着你在尝试将变量“directory”放入路径之前从未使用过它,也就是说,你从未使用过if(这很奇怪,因为你至少应该在某个时候点击根)你的代码在我的ubuntu上运行得很好。(减去末尾的打字错误)
该错误意味着您在尝试将名为“directory”的变量放入_path之前从未使用过它,也就是说,您从未使用过if(这很奇怪,因为您至少应该在某个点命中根)这里有一个更可移植的替代方法:
self._path = os.path.dirname(os.path.realpath(__file__))
替换您的循环这里有一个更便携的替代方案:
self._path = os.path.dirname(os.path.realpath(__file__))
替换你的循环