How to import python file(.py) into a 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.
问题答案:
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 *