I'm using Python in VS code. I am experiencing the error "no module named 'ch6'" when trying to import the functions from one file to another, where the files are located in two different folders.
I have two folders:
- "ch6" – which contain the file "RandomCharacter.py". This file has the functions I want to import.
- "ch7" – which contain the file "CountLettersInList.py" trying to import the functions from "RandomCharacter.py".
If I try to import the functions with the code:
import ch6.RandomCharacter
I get the error: "No module named 'ch6'"
If I use the code:
import RandomCharacter
I get the error: "No module named 'RandomCharacter'"
However, if I copy CountLettersInList.py from folder ch7 to folder ch6, the import works just fine with the code:
import RandomCharacter
So why can't it import the functions successfully when the files are in two different folders?
CodePudding user response:
The python import system can be annoying. Correct me if I'm wrong in any assumption I make! So what I understand is you're trying to import a RandomCharacter.py into a file located ch7/CountLettersInList.py?
The reason you can't import RandomCharacter.py into CountLettersInList.py is because what CountLettersInList.py can see is only in ch7. It can't even see the folder ch6.
Solution:
You have to go up one directory to see ch6. In order to do that tack these lines of code into CountLettersInList.py:
import sys
sys.path.append("..")
This goes up one directory to search for modules!
CodePudding user response:
Add the following code in CountLettersInList.py, then you can import successfully.
import sys
sys.path.append("./")

