简体   繁体   中英

{Import from File} Error when importing from other directory

I want to import a file from %appdata%/.EliteCS/sysfiles/gui.py however whenever I do, this comes up.

Traceback (most recent call last):
  File "C:\Users\Samuel\Documents\Elite\elite_computer_system.py", line 10, in <
module>
    import gui
ImportError: No module named gui

C:\Users\Samuel\Documents\Elite>pause
Press any key to continue . . .

My %appdata%/.EliteCS/sysfiles/ folder contains 2 files: __init__.py (empty py file) and gui.py, a py file full of definitions, but no actual code. When asking python to import it thus:

sys.path.insert(0, '%appdata%/.EliteCS/sysfiles')
import gui

it gives the error, same for from gui import * instead of the import gui line. Would someone please tell me what I am doing wrong. I can't work out what's wrong.

The %appdata% variable is not expanded by Python for you.

Either use an absolute path to the application data folder, or retrieve the %appdata% variable from the system and concatenate that with .EliteCS/sysfiles .

See How do I find the Windows common application data folder using Python? for methods to retrieve system paths like appdata .

If you use the environment option, that'd be:

import os
import sys

sys.insert(0, os.path.join(os.environ['APPDATA'], '.EliteCS', 'sysfiles'))

Why not place gui.py in the same folder as the file you are running? Then you can just say import gui and it will definitly run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM