This is an interesting problem so I spend a little time investigating. After some digging, it turns out the problem is there is already another script named "test.py" in one of the sys.path directories and Python is importing that script instead of the one you want.
When you import a module, Python looks for it in each of the search paths in the order they are listed in sys.path
and imports the first match. Using sys.path.append('path/to/folder')
fails because it adds a search path to the end of the list, and Python already finds a match for test.py
in one of the directories listed before it. This is also the reason sys.path.insert(0,'path/to/folder')
works - because it inserts the specified path at the front of the list so Python will find it first.
FIX
Change the name of the file 'test.py' to be something unique that won't match any other file names. This is the probably the best way.
You could use sys.path.insert(0,'path/to/folder')
which places the specified path first in the list of search paths.
Another way is to go through each of the directories in the sys.path list and remove or rename the other "test.py" file(s). Not recommended
is there any other way than sys
If both the script you are running and the script you want to import are in the same folder, you don't need sys
module.
If the files are in different folders and you absolutely won't use sys
, then you can set PYTHONPATH
in terminal before running the script. Note that you must run the python script from inside this same shell for it to work. Also, this will not work if the folder your script is in also contains a file with the same name as the one you want to import from another folder
Linux Bash:
export PYTHONPATH="path/to/folder/"
Windows Powershell:
set PYTHONPATH="path/to/folder/"