pythonpython-3.ximportmoduleimport-module

Cannot import name from a module


Can't import the function "ident" from "modulename"

def ident(key):
    import pandas as pd
    data = pd.read_csv("dicc.csv")
    data = data.T
    data = data.to_dict()
    print(data[0]["{}".format(clau)])

to my script

from modulename import ident

ImportError: cannot import name 'ident' from 'modulename' (/home/. . .)


Solution

  • Since you're a total beginner, here's a complete example:

    // modulename.py

    import pandas as pd
    
    
    def ident(key):
        data = pd.read_csv("dicc.csv")
        data = data.T
        data = data.to_dict()
        # Note: Here 'clau' is undefined, but maybe you have it elsewhere in your code
        print(data[0]["{}".format(clau)])
    

    // script.py

    #!/usr/bin/env python
    from modulename import ident
    
    print('look; I imported a function:', ident)
    

    Now you can run:

    $ python script.py
    

    or from some arbitrary directory it will work the same:

    $ cd ~
    $ python path/to/script.py
    

    Earlier I suggested adding something like this at the top of your script:

    import os
    import sys
    
    sys.path.insert(0, os.path.dirname(__file__))
    

    However, this should no longer be necessary, since when you run a Python script as your main module its directory automatically gets inserted at the beginning of sys.path, so it should just work.

    I suggest studying more about Python modules and the module search path (I realize it's annoying technical overhead when you just want to process some data, but if you're going to be using Python you'll thank yourself later by learning these concepts). Here's one such tutorial (no affiliation): https://realpython.com/python-modules-packages/