Using Python's os.path, how do I go up one directory?

前端 未结 14 1732
陌清茗
陌清茗 2020-12-07 07:47

I recently upgrade Django from v1.3.1 to v1.4.

In my old settings.py I have

TEMPLATE_DIRS = (
    os.path.join(os.path.dirname( __file_         


        
相关标签:
14条回答
  • 2020-12-07 08:11

    To go n folders up... run up(n)

    import os
    
    def up(n, nth_dir=os.getcwd()):
        while n != 0:
            nth_dir = os.path.dirname(nth_dir)
            n -= 1
        return nth_dir
    
    0 讨论(0)
  • 2020-12-07 08:14

    I think the easiest thing to do is just to reuse dirname() So you can call

    os.path.dirname(os.path.dirname( __file__ ))
    

    if you file is at /Users/hobbes3/Sites/mysite/templates/method.py

    This will return "/Users/hobbes3/Sites/mysite"

    0 讨论(0)
  • 2020-12-07 08:14
    from os.path import dirname, realpath, join
    join(dirname(realpath(dirname(__file__))), 'templates')
    

    Update:

    If you happen to "copy" settings.py through symlinking, @forivall's answer is better:

    ~user/
        project1/  
            mysite/
                settings.py
            templates/
                wrong.html
    
        project2/
            mysite/
                settings.py -> ~user/project1/settings.py
            templates/
                right.html
    

    The method above will 'see' wrong.html while @forivall's method will see right.html

    In the absense of symlinks the two answers are identical.

    0 讨论(0)
  • 2020-12-07 08:14

    This might be useful for other cases where you want to go x folders up. Just run walk_up_folder(path, 6) to go up 6 folders.

    def walk_up_folder(path, depth=1):
        _cur_depth = 1        
        while _cur_depth < depth:
            path = os.path.dirname(path)
            _cur_depth += 1
        return path   
    
    0 讨论(0)
  • 2020-12-07 08:14

    Go up a level from the work directory

    import os
    os.path.dirname(os.getcwd())
    

    or from the current directory

    import os
    os.path.dirname('current path')
    
    0 讨论(0)
  • 2020-12-07 08:17

    To get the folder of a file just use:

    os.path.dirname(path) 
    

    To get a folder up just use os.path.dirname again

    os.path.dirname(os.path.dirname(path))
    

    You might want to check if __file__ is a symlink:

    if os.path.islink(__file__): path = os.readlink (__file__)
    
    0 讨论(0)
提交回复
热议问题