Failed to load file while importing modules in python

Viewed 1358

This might be a repetition , but anyway straightly related to imports in python.

I have a directory structure like follows:

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

In sample.py

from utils import preprocess

In preprocess.py

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

Now the error is when I run sample.py IOError: [Errno 2] No such file or directory: '../Data/stopwords.txt' . I understand the crux of the error , because when I print the os.getcwd() in preprocess.py I get '/home/username/Main' .

But how to solve it . Any help would be appreciated

2 Answers

The code in preprocess.py is assuming a particular working directory. You can make this relative to the directory that preprocess.py is in.

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()
myfile = open("OpenEveningResults.csv", "a", newline="")

You may want to try using a different code to open or create the file before writing to or reading from it. You can use the code above as an example because it creates then [a] appends (appending is writing to a file making a new line each time) a CSV or Exel file.

Related