Relative paths in Python

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

    In the file that has the script, you want to do something like this:

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

    This will give you the absolute path to the file you're looking for. Note that if you're using setuptools, you should probably use its package resources API instead.

    UPDATE: I'm responding to a comment here so I can paste a code sample. :-)

    Am I correct in thinking that __file__ is not always available (e.g. when you run the file directly rather than importing it)?

    I'm assuming you mean the __main__ script when you mention running the file directly. If so, that doesn't appear to be the case on my system (python 2.5.1 on OS X 10.5.7):

    #foo.py
    import os
    print os.getcwd()
    print __file__
    
    #in the interactive interpreter
    >>> import foo
    /Users/jason
    foo.py
    
    #and finally, at the shell:
    ~ % python foo.py
    /Users/jason
    foo.py
    

    However, I do know that there are some quirks with __file__ on C extensions. For example, I can do this on my Mac:

    >>> import collections #note that collections is a C extension in Python 2.5
    >>> collections.__file__
    '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-
    dynload/collections.so'
    

    However, this raises an exception on my Windows machine.

提交回复
热议问题