Can't import from directory

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Cable
Posts: 2
Joined: Tue Apr 20, 2021 10:42 pm

Can't import from directory

Post by Cable » Tue Apr 20, 2021 10:52 pm

I am having issues importing python files from within a directory.

I have a boot.py file:

Code: Select all

from Spielwiesen import wifi

print("imported")
"Spielwiesen" is a directory containing example code snippets for if i forget something from time to time. Inside of Spielwiesen is the file "wifi.py". If I run the boot.py on my ESP32 it shows the following:

Code: Select all

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: no module named 'Spielwiesen.wifi'
I already tried creating a __init__.py file inside of Spielwiesen, but that also didn't help.

Here is also a quick os.listdir() in order to exclude the error source of me not flashing some of the files:

Code: Select all

['Spielwiesen\\__init__.py', 'Spielwiesen\\picoweb.py', 'Spielwiesen\\wifi.py', 'Spielwiesen', 'boot.py']
Also I am using the MicroPython Plugin for PyCharm to flash and run these files if that helps somehow.

Thanks in advance for your reply

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: Can't import from directory

Post by Roberthh » Wed Apr 21, 2021 8:33 am

You have to add the directory name "Spielwiesen" to sys.path.
sys.path.append("Spielwiesen")
then you can" import wifi".
Edit: Also: the path component separator is "/" not "\".

Cable
Posts: 2
Joined: Tue Apr 20, 2021 10:42 pm

Re: Can't import from directory

Post by Cable » Wed Apr 21, 2021 9:35 am

Hey Roberthh, thanks for your reply.
Roberthh wrote:
Wed Apr 21, 2021 8:33 am
You have to add the directory name "Spielwiesen" to sys.path.
sys.path.append("Spielwiesen")
I am going to try this and get back to this if I can confirm that this worked.
Roberthh wrote:
Wed Apr 21, 2021 8:33 am
Also: the path component separator is "/" not "\".
Hm I guess this is caused by the PyCharm Plugin that I use for flashing these files as I never used the "\" seperator explicitly myself when flashing.

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: Can't import from directory

Post by Roberthh » Wed Apr 21, 2021 11:31 am

Using the proper path separator is essential. Maybe you should put aside pycharm for a moment and use a simple terminal emulator like putty. Or use Thonny.
Without the proper file separator, Spielwiesen is not a directory, but just the part of a file name.

Post Reply