I tried writing some commenly used function in a seperate file and import the same into mainApp file, but not able to use import.
I did find many questions regarding the this same question but, the solution was to keep the files in the same folder
I tried without .py as well, but the same error:
Can you please help me how can i fix this issue ?
No '.py'. Just import seperate
Try using this in mainApp.py:
from seperate import *
a()
where seperate.py looks like this:
def a():
print('hi')
Well, sorry, those two files need to be in the same folder. This is not a solution to your problem.
The syntax of a relative import depends on the current location as well as the location of the module, package, or object to be imported. Here are a few examples of relative imports:
from .some_module import some_class
from ..some_package import some_function
from . import some_class
Read more about Absolute vs Relative Imports in Python
In your case it should be:
from .seperate import a
Also check this question:
Importing from a relative path in Python
add your project directory into your path variable so that python know from where you want to import file
Related
I have a file called hotel_helper.py from which I want to import a function called demo1, but I am unable to import it.
My hotel_helper.py file:
def demo1():
print('\n\n trying to import this function ')
My other file:
from hotel.helpers.hotel_helper import demo1
demo1()
but I get:
ImportError: cannot import name 'demo1' from 'hotel.helpers.hotel_helper'
When I import using from hotel.helpers.hotel_helper import * instead of from hotel.helpers.hotel_helper import demo1 it works and the function gets called. I tried importing the whole file with from hotel.helpers import hotel_helper and then call the function with hotel_helper.demo1() and it works fine. I don't understand what's wrong in first method. I want to directly import function rather using * or importing the whole file.
If you filename is hotel_helper.py you have to options how to import demo1:
You can import the whole module hotel_helper as and then call your func:
import hotel_helper as hh
hh.demo1()
You can import only function demo1 from module as:
from hote_helpers import demo1
demo1()
From your fileName import your function
from hotel.helpers import demo1
demo1()
You can import a py file with the following statement:
# Other import
import os
import sys
if './hotel' not in sys.path:
sys.path.insert(0, './hotel')
from hotel import *
NOTE:
For IDE like PyCharm, you can specify the import path using the Project Structure setting tab (CTRL+ALT+S)
Helpful stack overflow questions [maybe off topic]:
What is the right way to create project structure in pycharm?
Manage import with PyCharm documentation:
https://www.jetbrains.com/help/pycharm/configuring-project-structure.html
This is probably a duplicate of: https://stackoverflow.com/posts/57944151/edit
I created two files (defdemo.py and rundefdemo.py) from your posted 2 files and substituted 'defdemo' for 'hotel.helpers.hotel_helper' in the code. My 2 files are in my script directory for Python 3.7 on windows 10 and my script directory is in the python path file python37._pth. It worked.
defdemo.py
def demo1():
print('\n\n trying to import this function ')
rundefdemo.py
from defdemo import demo1
demo1()
output
trying to import this function
I was able to solve the issue, it was related to some imports I was making in my file, when I removed all the import statement in my hotel_helper.py ,the code started working as expected , Still I don't understand reason why the issue was occurring. anyway it works.
This ImportError can also arise when the function being imported is already defined somewhere else in the main script (i.e. calling script) or notebook, or when it is defined in a separate dependency (i.e. another module). This happens most often during development, when the developer forgets to comment out or delete the function definition in the body of a main file or nb after moving it to a module.
Make sure there are no other versions of the function in your development environment and dependencies.
I am trying to import files (python files) from another directory but it is not working as I have tried.
/pythonproject
.main.py
.__init__.py
->folder1
->.file1.py
->.file2.py
->.__init__.py
->folder2
->.functions.py
->.globals.py
->.__init__.py
I am trying to import functions.py inside of my file2.py.
I have tried
from functions import *
import functions
#file2.py
sys.path.insert(0, '/pythonproject')
import functions
I think your friend for this case is sys.path.append.
As discovered the problem is that you are importing the file, but when you went to use a function in the file you couldn't
One solution is:
import functions
functions.NameOfFunctionHere()
I am using Python 2.7 on Windows 7 Professional.
I am trying to call a function saved in another file to run in this file's code.
Function called dosomething is found in anotherfile.py
anotherfile.py is in the same directory as current code.
My call in this file is simple:
import anotherfile
print anotherfile.dosomething
I am getting an error: No module named anotherfile
The problem is the same as I found in this post
I don't understand the solution but I'd like any insight?
Thank you.
EDIT: The other question/answers discuss resetting CLASSPATH and setting PYTHONPATH. I explored this but was not sure how to do this. Perhaps relevant?
Let us have two files in the same directory. Files are called main.py and another.py.
First write a method in another.py:
def do_something():
return "This is the do something method"
Then call the method from main.py. Here is the main.py:
import another
print another.do_something()
Run main.py and you will get output like this:
This is the do something method
N.B.: The above code is being executed using Python 2.7 in Windows 10.
Specify the module then the file then the import like so:
from this_module.anotherfile import dosomething
or if you want all functions from "anotherfile.py"
from this_module.anotherfile import *
and then you can call the "dosomething" command without the "anotherfile" prefix.
I ran into same problem. After ample of trials, I ended up solving it with the below mentioned solution:
Make sure your current file and anotherfile.py lies in same location of system path.
Say your another.py and current file lies at location : "C:/Users/ABC"
In case, one is not aware of system path. Use below code in current file:
import sys
print(sys.path)
import sys
sys.path.append('/C:/Users/ABC/')
Then you do below code in same current code:
from another import dosomething
I found the issue. Python was looking in another directory for the files. I explicitly set my working directory as the path to where thisfile.py and anotherfile.py reside and it works. Thank you for all the quick replies.
I know this has been asked dozens of times but I can't see what in the world I'm doing wrong. I'm trying to import a module in python 2.7 from a different directory. I would greatly appreciate some input to help me understand why this method doesn't work. I have the following directory structure on my raspbian system:
/home/pi/
...projects/__init__.py
...projects/humid_temp.py
...python_utilities/__init.py__
...python_utilities/tools.py
I'm calling humid_temp.py and I need to import a function within tools.py This is what their contents look like:
humid_temp.py:
import os
import sys
sys.path.append('home/pi/python_utilities')
print sys.path
from python_utilities.tools import *
tools.py:
def tail(file):
#function contents
return stuff
The print sys.path output contains /home/pi/python_utilities
I'm not messing up my __init__.py's am I?
I've also ruled out possible permission issues with that path as I gave it full 777 access and I still hit the
ImportError: No module named python_utilities.tools.
What did I miss?
When you want to import something like -
from python_utilities.tools import *
You need to add the parent directory of python_utilities to sys.path , not python_utilities itself. So, you should add something like -
sys.path.append('/home/pi') #Assuming the missing of `/` at start was not a copy/paste mistake
Also, just a note, from <module> import * is bad , you should consider only importing the required items, you can check the question - Why is "import *" bad? - for more details.
In humid_temp.py, just write:
from python_utilities import tools
There is no need for appending subfolder to sys.path.
Then when you want to use functions from tools, just
tools.function()
I have two codefiles in python, let's say mainfile.py and separatecode.py. I would like to run separatecode.py from within mainfile.py, referencing the specific directory where separatecode.py is stored.
So the pseudocode of what I am looking to do would be something like:
import C:\Users\Jack\Documents\MyFolder\separatecode.py
A number of questions discuss importing, but I can't find one that discusses importing a specific file you wrote in a particular directory. I would like to be able to use functions defined in separatecode.py and am looking for the equivalent of the source("separatecode.r") command in R if that helps.
Add that directory to your sys.path by doing:
import sys
sys.path.append('/directory/to/my/file')
Import the module as normal:
import separatecode
The code you used will not work. It will give a syntax error.
Look at the documentation for the import statement, especially the grammar. A module is one or more identifiers separated by dots.
You can make import separatecode work by adding C:\Users\Jack\Documents\MyFolder to the PYTHONPATH environment variable. This will make it available to all Python scripts. Or you can add that path to sys.path in mainfile.py before importing separatecode.
Try something like this:
import imp
foo = imp.load_source('Module_name', 'Path\To\module.py')
foo.MyClass()
you dont need the foo.MyClass() it was just an example to show that the module works like any other module
no you can import a module from anywhere using the path and its name and you can acsess all its functions etc
for anything else check out:
Python Imp
I hope this is what you were looking for