gpt4 book ai didi

python - 使用 python 在 ubuntu 上附加目录

转载 作者:行者123 更新时间:2023-12-04 19:01:24 25 4
gpt4 key购买 nike

我想获取当前文件的目录,但是通过 os.path.abspath(__file__) , 我只能得到类似 /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文件。

最佳答案

这是一个更便携的替代方案:

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

dirname 替换你的循环

关于python - 使用 python 在 ubuntu 上附加目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45441333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com