简体   繁体   中英

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.

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 *

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM