Python에서 파일을 불러올 때 절대 경로(/home/path/example.txt) 혹은 상대 경로(./example.txt)로 지정하는 경우가 많다.
하지만 디렉토리 전체를 옮기거나 실행 자체를 다른 위치에서 하게 된다면 FileNotFoundError
가 발생할 수 있다.
실행 디렉토리의 위치에 상관 없이 실행 파일과 불러올 파일의 상대적인 관계만 안다면 다음과 같은 방법으로 에러를 차단할 수 있다.
import os
pwd = os.path.dirname(os.path.realpath(__file__)) # 현재 실행 중인 python 파일이 위치한 directory
file_path = os.path.join(pwd, "example.txt")
os.path.join()
메소드는 인자로 전달되는 string을 운영체제에 맞게 합쳐 file_path
를 생성한다.
또는
pwd = os.getcwd()
file_path = os.path.join(pwd, "example.txt")
os.path.join(pwd, "example.txt")
"/home/path/example.txt"
"C:\Users\path\example.txt"