2017-10-05 1 views
1

이것은 반복 일 수 있지만 어쨌든 파이썬에서 가져 오기와 직접 관련이 있습니다.파이썬에서 모듈을 가져 오는 동안 파일을로드하지 못했습니다.

Main/
sample.py 
utils/preprocess.py , __init__.py 
Data/stopwords.txt 

import codecs 
stopwords_ = codecs.open('../Data/stopwords.txt' , encoding='utf-8') 
stopwords_ = stopwords_.readlines() 

preprocess.py

에서
from utils import preprocess 

sample.py에서 내가 샘플을 실행하면 이제 오류는 다음과 같은

나는 디렉토리 구조를 가지고있다. py IOError : [Errno 2] 해당 파일이나 디렉토리가 없습니다 : '../Data/stopwords.txt'. preprocess.py에서 os.getcwd()를 인쇄 할 때 '/ home/username/Main'을 얻을 수 있기 때문에 오류의 핵심을 이해합니다.

하지만 어떻게 해결할 수 있습니까? 어떤 도움도 감사 할 것입니다.

+0

경로에서 "Data/stopwords.txt"를 사용하십시오. – planet260

+0

@ planet260 - 그건 내가 생각하기에 깔끔한 방법이 아닙니다. 나는 표준 해결책을 찾고있다. 감사 . –

답변

1

preprocess.py의 코드는 특정 작업 디렉토리라고 가정합니다. 당신은에 preprocess.py 디렉토리에이 상대적으로 만들 수 있습니다.

import codecs 
import os 
stopwords_file_path = os.path.join(
    os.path.dirname(__file__), 
    '../Data/stopwords.txt') 
stopwords_ = codecs.open(stopwords_file_path, encoding='utf-8') 
stopwords_ = stopwords_.readlines() 
+0

정말 고마워요. 대단히 필요하고 매우 유용합니다. –

0
myfile = open("OpenEveningResults.csv", "a", newline="") 

열거 나 서면 또는에서 읽기 전에 파일을 생성하기 위해 다른 코드를 사용하여 시도 할 수 있습니다. 위의 코드는 CSV 또는 Exel 파일을 추가하고 (추가 할 때마다 새 줄을 만드는 파일에 추가) CSV 또는 Exel 파일을 만들기 때문에 예제로 사용할 수 있습니다.

+0

그게 도움이되는지는 잘 모르지만 잘하면 모르겠다. – Dan

관련 문제