skip to Main Content

I’m currently learning Python, and I tried importing my own modules but first I got AttributeErrors and then I got ImportErrors (after trying another importing method) and even after searching for 3 hours for a solution I couldn’t find one.
Restarting VS Code and the Terminal several times and restarting my pc didn’t help either.
I was about to post my question here and to make it easier to see I moved my 3 files to a new folder.
Suddenly it worked without issues! Even after moving the files to the folder I got the errors from it still continued working. I didn’t change anything besides moving the files.

Could someone explain why that happend and what caused the errors?

It was structured like this (Code simplified and shortend):

First (didn’t work):

C:Users[User-ID]OneDriveDokumenteCodePythonhmanhangman_art.py

C:Users[User-ID]OneDriveDokumenteCodePythonhmanhangman_words.py

C:Users[User-ID]OneDriveDokumenteCodePythonhmanhangman05.py

Second (worked):

C:Users[User-ID]Desktophangman_art.py

C:Users[User-ID]Desktophangman_words.py

C:Users[User-ID]Desktophangman05.py

Then first again (worked too)

hangman_words.py
word_list = [
'abruptly', 
'absurd', 
'axiom'
]

hangman_art.py
logo = ''' 
 _                                             
| |                                            
| |__   __ _ _ __   __ _ _ __ ___   __ _ _ __  
| '_  / _` | '_  / _` | '_ ` _  / _` | '_  
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|__,_|_| |_|__, |_| |_| |_|__,_|_| |_|
                    __/ |                      
                   |___/    '''




hangman.py
import hangman_art 
import hangman_words 


print(hangman_art.logo)
print(hangman_words.word_list)




# Resutlted first in AttributeErrors:
AttributeError: module 'hangman_art' has no attribute 'logo' in Python

# Later in IndexErrors after I tried (from hangman_art import logo):
ImportError: cannot import name 'logo' from 'hangman_art'

2

Answers


  1. Chosen as BEST ANSWER

    The reason I got the Errors first but later not was because as I created the files to import (hangman_words.py and handman_art.py), I didnt save them. When you dont run the code in the file you created, it doesnt get autosaved. I had not closen it either (VS Code asks you if you want to save the changes in the file when you trying to close the tab). After I changed the location, the code in the files got saved, what had solved my importing problem. Thus it worked when I relocated them to the previous folder. Thats it!


  2. If your previous file does not exist in the same folder or is in a different subfolder, it is normal to have problems importing. In that case you can use the sys.path.append() method to specify the path to import the modules you need.

    Also more info about the import statement. Of course if you are willing to Google, you can get more useful information.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search