Python path.exists 和 path.join

问题描述 投票:0回答:3

Python 2.7: 与 path.exists 有点挣扎

import os
import platform
OS = platform.system()
CPU_ARCH = platform.machine()

if os.path.exists( os.path.join("/dir/to/place/" , CPU_ARCH) ):
    print "WORKED"
    # Linux
    LD_LIBRARY_PATH = "/dir/to/place/" + CPU_ARCH
    TRANSCODER_DIR  = LD_LIBRARY_PATH + "/Resources/"
else:
    print "FAILED"
    #fail back to original director if processor not recognised
    TRANSCODER_DIR  = "/dir/to/place/Resources/"
    LD_LIBRARY_PATH = "/dir/to/place"

一旦我将 os.path.join 与其中的变量粘贴在一起,if 语句就会失败。

os.path.exists("/dir/to/place/arch")

返回真

os.path.exists("/dir/to/place/" + CPU_ARCH)

返回假

我尝试了不同路径命令和字符串命令的多种变体,但没有一个允许我用变量来更改它。

os.path.join("/dir/to/place/", CPU_ARCH)

返回/dir/to/place/arch

这不是一个权限问题,也不是授予完全权限,而且我已经使用 python cli 进行了测试,它本身仍然存在同样的问题。

我已经查看了同一问题的所有堆栈帖子,我看到的唯一有人说有效的回复是删除空格,我对 python 很陌生,我没有看到任何空格.

python python-2.7 join path
3个回答
1
投票

os.path.exists
检查路径是否存在。

如果

/dir/to/place/arch
存在,则

os.path.exists("/dir/to/place/" + CPU_ARCH)

应该返回True。 注意您的示例中缺少

place
之后的 /

os.path.join
将连接其所有参数以创建路径。

# This joins the two arguments into one path
os.path.join("/dir/to/place/", CPU_ARCH)
# >>> '/dir/to/place/x86_64'

解释您的结果。


0
投票

如果

/dir/to/place/arch
存在,我建议将 arch 设置为
CPU_ARCH = platform.machine().strip()
,因为字符串末尾可能有空格,导致它失败。并可能将其设置为可供
LD_LIBRARY_PATH = var
重用的变量。


0
投票

这也可能有助于在路径中导航。

#current directory
os.path.abspath('.')
#parent directory
os.path.abspath('..')
#parent of parent directory
os.path.abspath('../..')
© www.soinside.com 2019 - 2024. All rights reserved.