问题
A very basic question that has been confusing me. Can't seem to find any solutions online so far...
I have a simple script and want to import another script I just made in the same directory.
What is the proper way of doing this?
I just tried combos of import myfile, from myfolder import myfile, import myfolder.myfile, etc
I get ImportError: No module named 'myfile'
Cheers
回答1:
This is because your current directory isn't on the PYTHON_PATH
, which is what import
searches when you call it. See the documentation.
If you want an immediate fix, you can use the following:
import sys, os
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
This adds the directory containing the script's file to the python path.
This will only work if the directory these scripts are in is set up as a package.
来源:https://stackoverflow.com/questions/22275056/importerror-no-module-named-basics