user2570937
user2570937

Reputation: 852

How do I import a python library from a different folder?

I'm using the adafruit python library for raspberry pi.

This is the file location I want to import to my file

/projectfolder/Adafruit-Raspberry-Pi-Python-Code/Adafruit_LEDBackpack/Adafruit_7Segment.py

And this is where the file is that i'm trying to import the library to

/projectfolder/start.py

I have this in start.py but it isn't working. Any idea why?

from Adafruit-Raspberry-Pi-Python-Code/Adafruit_LEDBackpack/Adafruit_7Segment import SevenSegment

This is the error i'm getting:

File "timer.py", line 5
    from Adafruit-Raspberry-Pi-Python-Code/Adafruit_LEDBackpack/Adafruit_7Segment import SevenSegment
                 ^
SyntaxError: invalid syntax

Upvotes: 0

Views: 7183

Answers (2)

Hun
Hun

Reputation: 3847

python import statement doesn't allow '-' in the variable name. However, you can still add that path to sys.path and make it working.

Check your sys.path first

>>> import sys
>>> print(sys.path)

If this does not include /projectfolder/Adafruit-Raspberry-Pi-Python-Code/Adafruit_LEDBackpack then add it to sys.path

>>> sys.path.append('/projectfolder/Adafruit-Raspberry-Pi-Python-Code/Adafruit_LEDBackpack')
>>> from Adafruit_7Segment import SevenSegment

Upvotes: 5

cuongnv23
cuongnv23

Reputation: 382

You put wrong path in the import statement, replace the dot with slash:

from Adafruit-Raspberry-Pi-Python-Code/Adafruit_LEDBackpack/Adafruit_7Segment import SevenSegment

Upvotes: 0

Related Questions