경로를 하드 코딩하지 않고 important_file.txt에 액세스하는 방법을 알고 싶습니다. myfile.py에서 일부 코드를 가져 오는 main.py를 실행합니다. 여기서는 important_file.txt를 읽어야합니다.이 작업을 수행하는 방법에 대한 아이디어가 있습니까?
파일 :
main.py
mydir/
mydir2/
myfile.py
important_file.txt
main.py
from mydir.mydir2.myfile import MyClass
MyClass.dostuff()
mydir / mydir2 / myfile.py
class MyClass:
def dostuff():
pass
# something to read important_file.txt
# without hardcoding it (writing mydir/mydir2/important_file.txt)
명령
python3 main.py
__file__
모듈의 경로를 읽는 데 사용할 수 있습니다 . 이후 myfile.py
와 important_file.txt
같은 디렉토리에있는 당신은 사용할 수 있습니다 os.path.dirname
귀하의 절대 경로 얻기 위해 디렉토리의 이름을 얻을하고 파일 이름으로 가입 .txt
파일을. 할 myfile.py
일 :
import os
class MyClass:
def dostuff():
dirname = os.path.dirname(__file__)
with open(os.path.join(dirname, "important_file.txt")) as f:
print(f.read())
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다