Something weird…
I was working on importing files from different folders..
and was working on python ide..
so my ide code:
>>> import os
>>> os.chdir("..")
>>> os.chdir("lib")
>>> os.chdir("native")
>>> os.getcwd()
'/.../.../Programming/lib/native'
>>> from category import *
works great..
but exactly same on my python file:
import os
import sys
#get current working directory
cur_dir = os.getcwd()
#move up one level
os.chdir("..")
new_cur_dir = os.getcwd()
print new_cur_dir
#move down to native
try:
os.chdir("lib")
print os.getcwd()
except IOError as e:
sys.exit("Exitting: 'lib' folder missing!!")
try:
os.chdir("native")
print os.getcwd()
from category import *
from pilottest import *
from datainstance import *
from similar import *
from collections import defaultdict
from item import *
from pilottest import *
from infernumber import *
except IOError as e:
sys.exit("Exitting: 'native' folder missing!!")
Error:
/../../Programming
/../../Programming/lib
/../../Programminglib/native
Traceback (most recent call last):
File "foo.py", line 25, in <module>
from category import *
ImportError: No module named category
When running code in the interpreter, the first entry of
sys.pathis an empty string, which indicates the current directory. However, when you run code from a file the first entry ofsys.pathis a fully qualified path of the directory that you ran the script from.This means that when you change directories in the interpreter you can always do imports from your current directory, but the same is not true for running from files.
If you want to always be able to import from the current directory in your scripts add the following lines to the top of your files: