在目录结构中向上移动

时间:2016-11-17 23:24:20

标签: python file directory relative

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

3 个答案:

答案 0 :(得分:1)

>>> os.getcwd()
'/Users/user/code'
>>> os.chdir('..')
>>> os.getcwd()
'/Users/user'

答案 1 :(得分:0)

目前还不清楚你要做什么,这里有两个选择:

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

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

答案 2 :(得分:0)

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

相关问题