Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import another python script (.py) into main python file

is there a way to import multiple python files into a main python file?

I have a bunch of py files and each one has to run in the main python file and the data are saved into a json file.

This is what I tried and it gave me an error.

import light.py as light 

Error:

Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 2218, in  _find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/pi/Desktop/majorproject/pillar1.py", line 8, in <module>
import sensorkey.py as sensorkey
ImportError: No module named 'sensorkey.py'; 'sensorkey' is not a package

I have also tried specifying the path to the py file and it didn't work either and keeps giving an invalid syntax error.

import /home/pi/Desktop/json/light.py as light

Update: I managed to fix the import error but i now, after importing this light.py file, i have to print out certain keys from a dictionary (key) into this new file then export it to a json file. I'm currently using TinyDB to do so. Here are my codes:

from tinydb import TinyDB, Query
import json
from light import key

with open("/home/pi/Desktop/json/sensortestest.json", 'w+'):
    db = TinyDB('/home/pi/Desktop/json/sensortestest.json')
    table = db.table('Light')
    db.insert_multiple([{'Key 1' :key[lightkey]}, {'Key 2' : key[lightkeyID]}])

Error:

Traceback (most recent call last):
  File "/home/pi/Desktop/majorproject/testertestest.py", line 12, in <module>
    db.insert_multiple([{'Key 1' :key[lightkey]}, {'Key 2' : key[lightkeyID]}])

NameError: name 'lightkey' is not defined

The problem is I had already defined 'lightkey' in its own file already.

like image 414
DanielWinser Avatar asked Jun 12 '17 04:06

DanielWinser


2 Answers

To include the dictionary, you could do this if your file location is in different directory (with caution of path.append as @Coldspeed mentioned):

import sys
sys.path.append("path/foo/bar/")
from light import *

If it is in same directory as current directory, you could just do:

from light import *
like image 192
nikpod Avatar answered Nov 20 '22 02:11

nikpod


The syntax for importing your_filename.py, assuming it is in the same directory, is

import your_filename

In your case, it would be

import light

Note the absence of .py.

If your file is in a different directory, you'll need to do:

import sys
sys.path.append('path/to/dir/containing/your_filename.py')
import your_filename

Note that appending to sys.path is dangerous, and should not be done unless you know what you're doing.

Read more at the official docs for import.

like image 28
cs95 Avatar answered Nov 20 '22 04:11

cs95