0

I have a folder present at the path /home/krishma/test. test folder contains a subfolders and python files.

example:
test -> db -> db.py

I want to use python files of test folder in second folder which is present at /user/scripts.

example:
scripts -> test -> test.py

In second folder, I have a file named test.py and I want to import db.py present in 1st test folder.

How can I import db.py in test.py?

wuerfelfreak
  • 2,363
  • 1
  • 14
  • 29

2 Answers2

0

You could read your current directory and manipulate the path as required.

import os
current_folder= os.getcwd()

for path manipulation have a look at https://docs.python.org/3/library/os.path.html

toto290
  • 29
  • 5
0

There are two approaches to this problem,

  1. Convert your db directory to package by adding init.py file to it.

To create package have a look at this-https://www.tutorialsteacher.com/python/python-package

  1. By modifying the sys.path.

When importing a file, Python only searches the directory that the entry-point script is running from and sys.path which includes locations such as the package installation directory (it's actually a little more complex than this, but this covers most cases).

However, you can add to the Python path at runtime:

# some_file.py
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '/path/to/application/app/folder')

import file

Have look at this-https://stackoverflow.com/questions/4383571/importing-files-from-different-folder

Prathamesh
  • 1,064
  • 1
  • 6
  • 16