Relative paths in Python

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

    0 讨论(0)
  • 2020-11-22 08:19

    As mentioned in the accepted answer

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

    I just want to add that

    the latter string can't begin with the backslash , infact no string should include a backslash

    It should be something like

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

    The accepted answer can be misleading in some cases , please refer to this link for details

    0 讨论(0)
  • 2020-11-22 08:19

    I'm not sure if this applies to some of the older versions, but I believe Python 3.3 has native relative path support.

    For example the following code should create a text file in the same folder as the python script:

    open("text_file_name.txt", "w+t")
    

    (note that there shouldn't be a forward or backslash at the beginning if it's a relative path)

    0 讨论(0)
提交回复
热议问题