0

I get that error message when I run python testscript.py I tried the recommendations given in link but was unsuccessful. My directory structure is as follows:

> bin
> - __init__.py
> - testscript.py
> 
> test2
> - __init__.py
> - printstring_module.py

And my code in testscript.py is as follows:

import sys
sys.path.append('C:\Users\KMF\Exercises\Projects\kevin_game\test2')
from test2 import printstring_module

printstring_module.printstrings("this is a test")
print("test over")

And the code for printstring_module.py is as follows:

def printstrings(string="you didn't provide a string"):
    print(string)

When I place both testscript.py and printstring_module.py in the same directory eg. bin folder the code works just fine.

Thanks and happy new year!

Community
  • 1
  • 1
ferry
  • 97
  • 6

1 Answers1

1

You are included the folder test2 in your path, so you should use something like this:

from printstring_module import printstrings

And then use printstrings function directly:

printstrings("this is a test")

Also rename init.py to __init__.py

EDIT:
You should also scape \ character. Try this code:

sys.path.append(r'C:\Users\KMF\Exercises\Projects\kevin_game\test2')

Note r i included before the opening quote.

Mehran Meidani
  • 341
  • 1
  • 13
  • I just tried this and resulted in this error message `ImportError: No module named printstring_module` – ferry Dec 31 '15 at 18:22
  • Also you should have an empty `__init__.py` in your folder. I edited my post, check it @ferry – Mehran Meidani Dec 31 '15 at 18:25
  • Hey my `__init__.py` are fine. Just that when I marked them as codes, SO removed the underscores. Code still doesn't work. – ferry Dec 31 '15 at 18:29
  • Put a `r` before the opening single quote to scape the `backslash` character. @ferry – Mehran Meidani Dec 31 '15 at 18:31
  • Wow, that worked. Could you please explain to me what the r did? – ferry Dec 31 '15 at 18:36
  • Good, please mark it as answered :) When you put `r` before the string, you tell python to consider it as raw string, so you shouldn't scape \ character. instead of `r`, you can use something like this : `c:\\Users\\...`. @ferry – Mehran Meidani Dec 31 '15 at 18:38