Python Forum

Full Version: importing functions from a separate python file in a separate directory
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So I can easily call a function from a file in the same directory as the one i'm running:
from functestsetup import functest
functest()
but it gets tricky when i attempt to do it from a different directory...
Error:
Traceback (most recent call last): File "O:\PyMemer BETA\functest.py", line 1, in <module> from functestsetup import functest ModuleNotFoundError: No module named 'functestsetup'
what I intend to do is have a subfolder of functions for the program to call upon, making the code way more efficient. Anyone have any ideas?
This works for me
myfunc.py in myfuncs folder
def print_it(arg):
    return arg
test.py
from myfuncs import myfunc
print(myfunc.print_it('Hello World!'))
Output:
Hello World!
Scordomaniac Wrote:but it gets tricky when i attempt to do it from a different directory...
You most think of where Python look for files/folders when not is same folder as code you run
Python look for files/folders in sys.path,so get in trouble if top level folder is not in sys.path.
look at how Packages works or some of my example here
In all my example so is top level folder in sys.path or run from virtual environment.
I am always making little functions.

When I have a lot of functions for 1 specific purpose, I save them as a module, then they are all available for that purpose.

For example, guiHTML.py has lots of functions for making html.

import os, sys    
# to import the files we need the paths
path = '/home/pedro/myPython/myModules/'

# append the paths
sys.path.append(path)

import tkinter as tk
    
from functools import partial      
import guiHTML
After that, all the functions are available.