使用Python的os.path,如何上传一个目录? [英] Using Python's os.path, how do I go up one directory?

查看:125
本文介绍了使用Python的os.path,如何上传一个目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



在我的旧的 settings.py 我有

  TEMPLATE_DIRS =(
os.path.join(os.path.dirname(__file__),'模板').replace('\\','/'),
#将字符串放在这里,如/ home / html / django_templates或C:/ www / django / templates
#总是使用正斜杠,甚至在Windows上
#不要忘记使用绝对路径,而不是相对路径

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



所以我的问题是n ow双重:


  1. 如何使用 os.path 查看目录从 __ file __ 以上一级。换句话说,我想要 /Users/hobbes3/Sites/mysite/mysite/settings.py 找到 / Users / hobbes3 / Sites / mysite /
  2. 我应该保留模板文件夹(具有交叉应用模板,例如项目 / User / hobbes3 / Sites的 admin 注册等) / mysite 级别或 / User / hobbes3 / Sites / mysite / mysite


解决方案

  os.path.abspath(os.path.join(os.path.dirname(__file__) ..','templates'))

至于模板文件夹应该去哪里,自从Django 1.4刚刚出来以来,我还没有看到它。你可能会在SE上提出另一个问题来解决这个问题。



你也可以使用 normpath 清理路径,而不是 abspath 。但是,在这种情况下,Django希望采用绝对路径而不是相对路径。



对于跨平台兼容性,请使用 os.pardir 而不是'..'


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__ ), '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.
)

This will point to /Users/hobbes3/Sites/mysite/templates, but because Django v1.4 moved the project folder to the same level as the app folders, my settings.py file is now in /Users/hobbes3/Sites/mysite/mysite/ instead of /Users/hobbes3/Sites/mysite/.

So actually my question is now twofold:

  1. How do I use os.path to look at a directory one level above from __file__. In other words, I want /Users/hobbes3/Sites/mysite/mysite/settings.py to find /Users/hobbes3/Sites/mysite/templates using relative paths.
  2. Should I be keeping the template folder (which has cross-app templates, like admin, registration, etc.) at the project /User/hobbes3/Sites/mysite level or at /User/hobbes3/Sites/mysite/mysite?

解决方案

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 '..'.

这篇关于使用Python的os.path,如何上传一个目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆