Relative paths in Python

前端 未结 15 1663
陌清茗
陌清茗 2020-11-22 07:39

I\'m building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don\'t, however, have the absolute path

15条回答
  •  醉梦人生
    2020-11-22 07:55

    See sys.path As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.

    Use this path as the root folder from which you apply your relative path

    >>> import sys
    >>> import os.path
    >>> sys.path[0]
    'C:\\Python25\\Lib\\idlelib'
    >>> os.path.relpath(sys.path[0], "path_to_libs") # if you have python 2.6
    >>> os.path.join(sys.path[0], "path_to_libs")
    'C:\\Python25\\Lib\\idlelib\\path_to_libs'
    

提交回复
热议问题