我最近把Django从v1.3.1升级到了v1.4。

在我的旧设置。py我有

TEMPLATE_DIRS = (
    os.path.join(os.path.dirname( __file__ ), 'templates').replace('\\', '/'),
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

这将指向/Users/hobbes3/Sites/mysite/templates,但因为Django v1.4将项目文件夹移动到与应用文件夹相同的级别,我的settings.py文件现在在/Users/hobbes3/Sites/mysite/而不是/Users/hobbes3/Sites/mysite/。

所以实际上我的问题是双重的

如何使用操作系统。查看__file__上一级目录的路径。换句话说,我想要/Users/hobbes3/Sites/mysite/ settings.py使用相对路径找到/Users/hobbes3/Sites/mysite/templates。 我应该保持模板文件夹(其中有跨应用模板,如管理,注册等)在项目/User/hobbes3/Sites/mysite级别或在/User/hobbes3/Sites/mysite/mysite?


当前回答

要向上移动n个文件夹…运行了(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

其他回答

对我这样的偏执狂来说,我更喜欢这个

TEMPLATE_DIRS = (
    __file__.rsplit('/', 2)[0] + '/templates',
)

要向上移动n个文件夹…运行了(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

这在其他情况下很有用当你想往上移动x个文件夹时。只需要运行walk_up_folder(path, 6)就可以找到6个文件夹。

def walk_up_folder(path, depth=1):
    _cur_depth = 1        
    while _cur_depth < depth:
        path = os.path.dirname(path)
        _cur_depth += 1
    return path   

使用os。我们可以向上走一个目录

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

同样,在找到您想要的目录后,您可以与其他文件/目录路径连接

other_image_path = os.path.join(one_directory_up_path, 'other.jpg')

如果你使用的是Python 3.4或更新版本,一个方便的方法是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])  # "."