Programming

파이썬의 os.path를 사용하여 하나의 디렉토리를 어떻게 올라갈 수 있습니까?

procodes 2020. 5. 16. 11:18
반응형

파이썬의 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만, 장고 V1.4는 응용 프로그램 폴더와 같은 수준으로 프로젝트 폴더를 이동하기 때문에 , 내 settings.py파일에 지금 /Users/hobbes3/Sites/mysite/mysite/대신 /Users/hobbes3/Sites/mysite/.

실제로 내 질문은 이제 두 가지입니다.

  1. 어떻게 사용합니까 os.path에서 위의 디렉토리 한 수준에서보고 __file__. 즉, 상대 경로를 사용하여 /Users/hobbes3/Sites/mysite/mysite/settings.py찾고 싶습니다 /Users/hobbes3/Sites/mysite/templates.
  2. 나는 유지되어야한다 template(교차 응용 프로그램 템플릿 같은이 폴더 admin, registration프로젝트에서, 등) /User/hobbes3/Sites/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대신을 사용하십시오 '..'.


파일의 폴더를 얻으려면 다음을 사용하십시오.

os.path.dirname(path) 

폴더를 가져 오려면 os.path.dirname다시 사용 하십시오.

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

__file__심볼릭 링크 인지 확인하고 싶을 수도 있습니다 .

if os.path.islink(__file__): path = os.readlink (__file__)

당신은 이것을 정확히 원합니다 :

BASE_DIR = os.path.join( os.path.dirname( __file__ ), '..' )

개인적으로, 나는 기능 접근을 위해 갈 것입니다

def get_parent_dir(directory):
    import os
    return os.path.dirname(directory)

current_dirs_parent = get_parent_dir(os.getcwd())

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])  # "."

가장 쉬운 방법은 dirname ()을 재사용하는 것입니다.

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

파일이 /Users/hobbes3/Sites/mysite/templates/method.py에있는 경우

"/ Users / hobbes3 / Sites / mysite"를 반환합니다.


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

심볼릭 링크가 없으면 두 답변이 동일합니다.


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   

나 같은 편집증의 경우, 나는 이것을 선호합니다

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

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

물론 : 간단히 사용하십시오 os.chdir(..).

참고 URL : https://stackoverflow.com/questions/9856683/using-pythons-os-path-how-do-i-go-up-one-directory

반응형