Why can't Python import a file from a relative path? - python

I found this question helpful, but Python is unable still to find the folder.
I have a Django folder structure that looks like this:
todoproject
pythonDiscordChatbot
processLessons.py
todoapp
testChatFunctions.py
I'm trying to import a function called 'routes' into testChatFunctions.py, but I keep getting this error:
File "c:\Users\Kaij\Documents\chatSiteDjango\todoproject\todoapp\testChatFunctions.py", line 6, in <module>tSiteDjango\todoproject\todoapp\tesssLesson import *tChatFunctions.py", line 6, in <modd 'pythonDiscordChatbot'ule> atSiteDjango> & C:/Users/Kaij/Documents/djangoTests/django_tailwind_project/env/Scripts/
from pythonDiscordChatbot.procechatSiteDjango/todoproject/todoapp/testChatFunctions.pyssLesson import *
ModuleNotFoundError: No module nametSiteDjango\todoproject\todoapp\testChatFunctions.py", line 6, in <module>d 'pythonDiscordChatbot
Here's what I have tried:
# Bring your packages onto the path
import sys, os
sys.path.append(os.path.abspath(os.path.join('..', 'pythonDiscordChatbot')))
# Now do your import
from pythonDiscordChatbot.processLesson import *
# from pythonDiscordChatbot.processLesson import routes
routes("hello", "website_180.02.1")

Related

I can not figure out why I can not start this simlple python script

My directory looks like this
When I start directly with PyCharm it works.
But when I try to start the script with a commandline I get this error messsage
> python .\PossibilitiesPlotter.py
Traceback (most recent call last):
File "C:\Users\username\PycharmProjects\SwapMatrixPlotter\possibilitiesplotter\PossibilitiesPlotter.py", line 7, in <module>
from plotterresources.PlotterProps import PlotterProps
ModuleNotFoundError: No module named 'plotterresources'
This is how the import looks from my main class PossibilitesPlotter.py
import sys
sys.path.append("plotterresources/PlotterProps.py")
from csv import reader
from pathlib import Path
from plotterresources.PlotterProps import PlotterProps
from possibilitiesplotter.PossibilitiesGraph import PossibilitiesGraph
from possibilitiesplotter.PossibilitiesModel import PossibilitiesModel
class PossibilitiesPlotter:
As a workaround, add the following line to PossibilitesPlotter.py:
sys.path.append("../plotterresources/PlotterProps.py")
This will add the directory one level above the commandline pwd to the PATH variable. So this is always relative to the location of the calling script/shell.
Thus in general:
NEVER append to the PATH/PYTHONPATH variable from within modules. Instead restructure your module. For more details, take a look at the documentation on Packaging Python Projects

ModuleNotFoundError: No module named 'createCredentialsXML'

I have a question about my new python project. It is the first time that I use different folders for my project.
I have the following structure:
project
src
securityFunc
__init__.py
createCredentialsXML.py
main.py
I work in PyCharm environment.
After pressing Play i get the error message:
Traceback (most recent call last):
File "C:\project\src\main.py", line 1, in <module>
from securityFunc import *
File "C:\project\src\securityFunc\__init__.py", line 1, in <module>
from createCredentialsXML import *
ModuleNotFoundError: No module named 'createCredentialsXML'
My main function looks like this:
from securityFunc import *
if __name__ == '__main__':
generate_key()
__init__.py:
from createCredentialsXML import *
createCredentialsXML.py:
def generate_key():
key = base64.urlsafe_b64encode(os.urandom(2048))
with open("../key/secret.key", "wb") as key_file:
key_file.write(key)
I tried using Path or sys.path to fix the problem. But it does not work.
Can you please tell me how to fix the problem?
Since you're doing a relative import, you need to add a . before your module name:
from .createCredentialsXML import *
The dot means the module is found in the same directory as the code importing the code.
You can read more about it here
createCredentialsXML.py works in the module securityFunc; you must specify the scope of the import. Using
from securityFunc.createCredentialsXML import *
in securityFunc.__init__.py should work.

import in python file has imported file

I have python project like
/project
|__main.py
|__/graph
|____grapher.py
|____object_map_genaration.py
In grapher: import object_map_genaration
In main: import grapher
But I got this error:
ModuleNotFoundError: No module named 'object_map_genaration'
First add an init here:
/project/
|__/main.py
|__/graph/
|____/__init__.py
|____/grapher.py
|____/object_map_genaration.py
Then in grapher.py:
from . import object_map_genaration
And in main.py:
from graph import grapher
You need from grapher import object_map_genaration not just import object_map_genaration, since imports are relative to the root of the main file.

Import errors on VS code

I'm new to VS code. I have downloaded a git project which has demo programs that I can run.
The directory structure is as follows:
Projectparser
>demo
>>alg1_demo.py
>>alg2_demo.py
>>alg3_demo.py
>Projectparser
>>alg1
>>>__init__ [ Has just one line : from alg1 import * ]
>>>alg1.py
>>>calg1.c
>>>calg1.h
>>alg2
>>>__init__ [ Has just one line : from alg2 import * ]
>>>alg2.py
>>>calg2.c
>>>calg2.h
>>alg3
>>>__init__ [ Has just one line : from alg3 import * ]
>>>alg3.py
>>>calg3.c
>>>calg3.h
where > indicates sub-directory. Projectparser is the folder from where I open vs code. It has a sub-directory by the same name as well which contains all the algorithms I'm interested in.
When I try running the alg1_demo.py. The below line is causing an error.
sys.append("../")
from Projectparser import alg1 (line 8)
I'm getting the following error:
ImportError: cannot import name 'alg1' from 'Projectparser' (unknown location)
So I added the line : sys.path.append("../Projectparser")
Then I'm getting the following error :
File "/home/suneha/Projectparser/demo/alg1_demo.py", line 8, in <module>
from Projectparser import alg1
File "../Projectparser/Projectparser/alg1/__init__.py", line 1, in <module>
from alg1 import *
ModuleNotFoundError: No module named 'alg1'
But the module is present in the subdirectory. So I added the line :
sys.path.append("../Projectparser/Projectparser/alg1")
Then I'm getting this error :
Traceback (most recent call last):
File "/home/suneha/Projectparser/demo/alg1_demo.py", line 8, in <module>
from Projectparser import alg1
File "../Projectparser/Projectparser/alg1/__init__.py", line 1, in <module>
from alg1 import *
File "/home//Projectparser/Projectparser/alg1/alg1.py", line 13, in <module>
from ..logmatch import regexmatch
ImportError: attempted relative import with no known parent package
The same problem persists for all the three algorithms alg1, alg2, alg3. I'm not sure how to fix this and is using sys.append.path() the best way to solve the above mentioned problems.
Can anyone suggest how to solve the final import error : ImportError: attempted relative import with no known parent package
and if there is any other compact way of solving the other import errors instead of using sys.path.append().
Thanks in advance
Use the following statement to add the path of the file that needs to be imported to the system path to help VSCode find it:
import os,sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
The following is part of the project I created that you provided:
Result:
The following points need to be noted:
When importing, the subfolders are connected with.
Please avoid using files and folders with the same name to prevent confusion when VSCode finds modules.
If the result is executable but there is still a wave line, you can add in settings.json: "python.linting.pylintArgs": [ "----extension-pkg-whitelist=1xml" ],
Update:
According to the code of the link you provided, I reproduced the problem you described locally, and the solution is as follows:
Comment out the content "from SLCT import *" of logparser-master\logparser\SLCT_init_.py.
Add import os,sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
to SLCT_demo.py
operation result:

Imported module fails to import sub-module

I have the following folder-structure
premier_league/
|_cli_stats/
|__ __init__.py
|__cli_stats.py
|__get_data/
|__get_stats.py
|__get_id.py
|__api_scraper/
|__api_scraper.py
In cli_stats.py I have the following import:
from get_data.get_stats import SeasonStats
In get_stats.py I have the following import:
from api_scraper.api_scraper import Football.
When running python cli_stats.py from the cli_stats folder the following error occurs.
File "cli_stats.py", line 36, in <module>
from get_data.get_stats import SeasonStats
File "/Users/name/Desktop/Projekt/premier_league_api/cli_stats/get_data/get_stats.py", line 12, in <module>
from api_scraper.api_scraper import Football
ModuleNotFoundError: No module named 'api_scraper'
But when running python get_stats.py from the get_data folder, the import is successful. Why does the import not work when running cli_stats.py from the cli_stats folder?
You have to adjust the import to a relativ one. From theget_stats.pyyou have to step into the directory. The error is that from api_scraper.api_scraper import Football is an absolut import.
Try: in get_stats.py
from .api_scraper.api_scraper import Football
(1 dot before the api_scraper)

Categories

Resources