close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to import files in python using sys.path.append in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

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

    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.

  2. import files in python using sys.path.append

    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.

Method 1


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.

Method 2

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 path

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

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read