Relative paths in Python

前端 未结 15 1495
陌清茗
陌清茗 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 08:15

    Instead of using

    import os
    dirname = os.path.dirname(__file__)
    filename = os.path.join(dirname, 'relative/path/to/file/you/want')
    

    as in the accepted answer, it would be more robust to use:

    import inspect
    import os
    dirname = os.path.dirname(os.path.abspath(inspect.stack()[0][1]))
    filename = os.path.join(dirname, 'relative/path/to/file/you/want')
    

    because using __file__ will return the file from which the module was loaded, if it was loaded from a file, so if the file with the script is called from elsewhere, the directory returned will not be correct.

    These answers give more detail: https://stackoverflow.com/a/31867043/5542253 and https://stackoverflow.com/a/50502/5542253

提交回复
热议问题