I have been attempting to define a python function in one script (lets call it script1.py) like so:
def fn1():
print("Hello")
and then to import it into a separate python file in the same directory (lets call it script2.py) like this:
from script1 import fn1
or import script1
I've found lots of posts/answers supporting this process, but I continue to receive the error message that there is "No module named 'script1'". Most of the posts I've seen are from 3+ years ago, so perhaps the newer versions of python have terminated this option.
I appreciate any solutions!
If your two files are in the same folder, you can try adding a blank __init__.py file to your folder and using a relative import:
from .script1 import fn1
Adding the '.' before the module name ensures that your script is looking in the current directory.
To specify the parent directory, try: from {folder_name}.script1 import fn1
where folder_name is parent directory
You can read more about relative imports in Python 3 documentation .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.