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

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

    For a paranoid like me, I'd prefer this one

    TEMPLATE_DIRS = (
        __file__.rsplit('/', 2)[0] + '/templates',
    )
    
    0 讨论(0)
  • 2020-12-07 08:26

    Of course: simply use os.chdir(..).

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

    With using os.path we can go one directory up like that

    one_directory_up_path = os.path.dirname('.')
    

    also after finding the directory you want you can join with other file/directory path

    other_image_path = os.path.join(one_directory_up_path, 'other.jpg')
    
    0 讨论(0)
  • 2020-12-07 08:29

    If you are using Python 3.4 or newer, a convenient way to move up multiple directories is pathlib:

    from pathlib import Path
    
    full_path = "path/to/directory"
    str(Path(full_path).parents[0])  # "path/to"
    str(Path(full_path).parents[1])  # "path"
    str(Path(full_path).parents[2])  # "."
    
    0 讨论(0)
  • 2020-12-07 08:29

    Personally, I'd go for the function approach

    def get_parent_dir(directory):
        import os
        return os.path.dirname(directory)
    
    current_dirs_parent = get_parent_dir(os.getcwd())
    
    0 讨论(0)
  • 2020-12-07 08:34
    os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'templates'))
    

    As far as where the templates folder should go, I don't know since Django 1.4 just came out and I haven't looked at it yet. You should probably ask another question on SE to solve that issue.

    You can also use normpath to clean up the path, rather than abspath. However, in this situation, Django expects an absolute path rather than a relative path.

    For cross platform compatability, use os.pardir instead of '..'.

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