问题:使用Python的os.path,如何进入一个目录?
我最近将Django从v1.3.1升级到v1.4。
我以前settings.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/mysite/
而不是/Users/hobbes3/Sites/mysite/
。
所以实际上我的问题是双重的:
- 如何使用
os.path
来查看上一级目录__file__
。换句话说,我想/Users/hobbes3/Sites/mysite/mysite/settings.py
找到/Users/hobbes3/Sites/mysite/templates
使用相对路径。
- 我应该保持
template
(其具有跨应用程序模板,如文件夹admin
,registration
在项目等)/User/hobbes3/Sites/mysite
水平或在/User/hobbes3/Sites/mysite/mysite
?
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:
- 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.
- 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
?
回答 0
os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'templates'))
至于template文件夹应该放哪里,我不知道自从Django 1.4刚问世以来,我还没有看过它。您可能应该在SE上问另一个问题以解决该问题。
您也可以使用normpath
来清理路径,而不是abspath
。但是,在这种情况下,Django需要绝对路径而不是相对路径。
为了实现跨平台兼容性,请使用os.pardir
代替'..'
。
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 '..'
.
回答 1
要获取文件的文件夹,请使用:
os.path.dirname(path)
要建立文件夹,只需os.path.dirname
再次使用
os.path.dirname(os.path.dirname(path))
您可能要检查是否__file__
为符号链接:
if os.path.islink(__file__): path = os.readlink (__file__)
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__)
回答 2
如果您使用的是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]) # "."
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]) # "."
回答 3
您正是想要这样的:
BASE_DIR = os.path.join( os.path.dirname( __file__ ), '..' )
You want exactly this:
BASE_DIR = os.path.join( os.path.dirname( __file__ ), '..' )
回答 4
就个人而言,我会选择功能方法
def get_parent_dir(directory):
import os
return os.path.dirname(directory)
current_dirs_parent = get_parent_dir(os.getcwd())
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())
回答 5
我认为最简单的方法就是重用dirname(),因此您可以调用
os.path.dirname(os.path.dirname( __file__ ))
如果文件位于/Users/hobbes3/Sites/mysite/templates/method.py
这将返回“ / Users / hobbes3 / Sites / mysite”
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”
回答 6
from os.path import dirname, realpath, join
join(dirname(realpath(dirname(__file__))), 'templates')
更新:
如果您碰巧settings.py
通过符号链接“复制” ,@ forivall的答案会更好:
~user/
project1/
mysite/
settings.py
templates/
wrong.html
project2/
mysite/
settings.py -> ~user/project1/settings.py
templates/
right.html
上面的方法将“看到”,wrong.html
而@forivall的方法将看到right.html
在没有符号链接的情况下,两个答案是相同的。
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.
回答 7
这对于在其他情况下需要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
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
回答 8
对于像我这样的偏执狂,我更喜欢这个
TEMPLATE_DIRS = (
__file__.rsplit('/', 2)[0] + '/templates',
)
For a paranoid like me, I’d prefer this one
TEMPLATE_DIRS = (
__file__.rsplit('/', 2)[0] + '/templates',
)
回答 9
打开n
文件夹…运行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
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
回答 10
Of course: simply use os.chdir(..)
.
回答 11
通过使用,os.path
我们可以像这样建立一个目录
one_directory_up_path = os.path.dirname('.')
在找到您想要的目录之后,您还可以与其他文件/目录路径一起加入
other_image_path = os.path.join(one_directory_up_path, 'other.jpg')
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')