【问题标题】:In Python, how should one test for the existence of a file in a path specified in an environment variable?在 Python 中,应该如何测试环境变量中指定的路径中是否存在文件?
【发布时间】:2015-04-05 09:20:37
【问题描述】:

我想检查以下文件是否存在:

$ANALYSISDIRECTORY/data/AnalysisDerivative/configuration.txt

目前,我有一个小功能来确保文件存在:

def ensureFileExistence(fileName):
    log.debug("ensure existence of file {fileName}".format(
        fileName = fileName
    ))
    if not os.path.isfile(fileName):
        log.info("file {fileName} does not exist\n".format(
            fileName = fileName
        ))
        sys.exit()

我应该如何让这个函数更健壮,并且能够处理存储在环境变量中的路径和路径?

【问题讨论】:

    标签: python bash path environment-variables system


    【解决方案1】:

    为了确保您访问的是环境变量的值而不是它的字符串表示,您可以使用os.path.expandvars

    如果您要测试的路径在环境变量中,您可以使用os.getenv

    【讨论】:

    • 啊,感谢您在扩展 shell 变量的过程中提供的帮助。我现在正在使用测试os.path.isfile(os.path.expandvars(fileName))
    • 最好使用本地变量来旧路径的扩展值,以避免在打印操作路径时重复对expandvars的调用
    • @bvidal 在用户的本地 bashrc 中设置的环境变量怎么样?您可以使用 echo $ 看到它们,但不能通过 printenv 或使用 os.getenv
    • 我可以通过os.getenv("PS1")在我的 bashrc 中检索我的提示 env var 定义
    • @bvidal hmmm .. 在我的最后似乎有些可疑。当您使用 printenv 时,您的 PS1 会出现吗?
    【解决方案2】:

    代替

     if not os.path.isfile(fileName):
    

    使用

     if not os.path.exists(fileName):
    

    【讨论】:

    • 感谢您的想法。在这种情况下,我认为bvidal 的变量扩展方法suggested 是有意义的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 2017-08-30
    • 2011-05-19
    • 2014-11-14
    • 2020-12-12
    • 1970-01-01
    相关资源
    最近更新 更多