【问题标题】:Move up in directory structure在目录结构中上移
【发布时间】:2016-11-17 23:24:19
【问题描述】:

假设我正在C:\temp\templates\graphics 中运行 Python 脚本。我可以使用currDir = os.getcwd() 获取当前目录,但是如何使用相对路径在目录中向上移动并在C:\temp\config 中执行某些操作(注意:此文件夹不会总是在C:\ 中)?

【问题讨论】:

  • 你到底想做什么?如果这是您的 Python 程序的 /config,请考虑将其作为模块的一部分,而不是使用工作目录。
  • 您在寻找os.chdir('..')吗?
  • 哦,我刚试过这个。这看起来很有希望。所以,我可以使用它向上移动,然后再次执行 os.getcwd() 来获取目录。谢谢
  • os.path 提供了一系列可能满足您需求的选项。我不清楚您的实际需求是什么,但 os.path.relpath(path[, start]) 可能有用吗?

标签: python file directory relative-path


【解决方案1】:
>>> os.getcwd()
'/Users/user/code'
>>> os.chdir('..')
>>> os.getcwd()
'/Users/user'

【讨论】:

    【解决方案2】:

    不清楚您要做什么,这里有两种选择:

    要更改进程的当前工作目录“向上”路径:

    os.chdir('../../config')
    

    或者,使用相对路径名打开文件:

    with open('../../config/my_config.ini') as cfg_file:
        pass
    

    当然,如果您确实更改了当前工作目录,那么您的 open() 参数也应该更改:

    os.chdir('../../config')
    with open('my_config.ini') as cfg_file:
        pass
    

    【讨论】:

      【解决方案3】:

      试试这个: os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "config")

      【讨论】:

        猜你喜欢
        • 2016-10-27
        • 2014-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-11
        • 2013-10-09
        • 1970-01-01
        相关资源
        最近更新 更多