How to import files in python using sys.path.append?

How to import files in python using sys.path.append?

You can create a path relative to a module by using a modules __file__ attribute. For example:

myfile = open(os.path.join(
    os.path.dirname(__file__),
    MY_FILE))

This should do what you want regardless of where you start your script.

Replace

MY_FILE = myfile.txt
myfile = open(MY_FILE) 

with

MY_FILE = os.path.join(DIR2, myfile.txt)
myfile = open(MY_FILE) 

Thats what the comments your question has are referring to as the relative path solution. This assumes that youre running it from the dir one up from myfile.txt… so not ideal.

If you know that my_file.txt is always going to be in the same dir as file2.py then you can try something like this in file2..

from os import path

fname =  path.abspath(path.join(path.dirname(__file__), my_file.txt))
myfile = open(fname)

How to import files in python using sys.path.append?

Leave a Reply

Your email address will not be published.