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

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


You can create a path relative to a module by using a module's __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) 

That's what the comments your question has are referring to as the relative path solution. This assumes that you're 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 pathfname =  path.abspath(path.join(path.dirname(__file__), "my_file.txt"))myfile = open(fname)