파이썬 상위,하위,특정 디렉토리에 있는 패키지 임포트하기(import)

2020. 4. 25. 21:56분석 Python/구현 및 자료

728x90

광고 한 번씩 눌러주세요! 블로그 운영에 큰 힘이 됩니다 :)

하위 디렉터리에서 import 하기

특정 폴더 안에 파일을 넣어놓았다고 하자.

이때 폴더 이름에 얽매이지 않고 안에 있는 패키지를 쓰고 싶다고 해보자.

예를 들어 폴더 이름이 test_folder 이든 test_folder2이든 안에 있는 check.py , check2.py를 쓰고 싶다고 하자.

이럴 때는 일단 __init__. py를 추가하면 된다. 그냥 저 파일만 생성을 해주면 된다.

이제 상위 디렉토리에 있는 주피터 노트북으로 하위 디렉터리 test_folder2에 있는 check.py를 사용해보자

test_folder2에 있는 check에서 method를 import 할 때 check2.py에 있는 것도 같이 임포트 시킨 것을 확인하였다.

먄약 __init__. py 파일을 지운다면 어떻게 될까? 

 

 

import는 되지만 찾는 것에서 인식을 하지 못한다.

하지만 __init__. py 파일이 있다면 저렇게 안에 있는 script를 인식하게 해주는 것 같다.

 

Files name __init__.py are used to mark directories on disk as Python package directories. If you have the files
If you remove the __init__.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.
The __init__.py file is usually empty, but can be used to export selected portions of the package under more convenient name, hold convenience functions, etc. Given the example above, the contents of the init module can be accessed as

 

__init__.py 은 디스크의 디렉터리를 파이썬 패키지 디렉터리로 표시하는 데 사용된다고 한다.

 


상위 디렉터리에서 import 하기

 

상위 디렉토리 파일을 임포트 할 때 생기는 오류는 다음과 같다.

ImportError: attempted relative import with no known parent package

ValueError: attempted relative import beyond top-level package

주피터에서 만약 하고 싶다면 다음과 같이 해야 한다.

import sys
sys.path.append("..")
from parent_script import *

script에서 한다고 하면 굳이 저렇게 안 해도 된다고 아래 글에서는 말한다.

script에서 -m 옵션을 줘서 실행하면 상위 디렉터리까지 import 할 수 있다.

from ..parent_script import *

python -m ###.py

 

 

https://m.blog.naver.com/wideeyed/221839634437

 

[Python] relative import with package info

파이썬에서 디렉토리를 이용하여 패키지를 관리할 수 있습니다.그런데 하위 패키지만 사용하지 않고 상위 ...

blog.naver.com


특정 디렉터리에서 import 하기

만약 /home/parent/child/child2라는 폴더에 있는 script를 import 하고 싶다고 하자.

그러면 sys.path.append로 추가하면 된다.

import sys
sys.path.append("/home/parent/child/child2")

 

 

 

https://pythontips.com/2013/07/28/what-is-__init__-py/

 

What is __init__.py ?

Okay yet another useful post. This post is really important and useful for anyone just starting out with python. So what is the __init__.py file ?

pythontips.com

 

728x90