Sword Slash
Sword Slash

Reputation: 17

How to import a file in another folder

recently I have been making a python project, but my files were too messy and I decided to group my files into folders. However, I am now struggling to import a file from another directory/folder

My code:

# Imports
import random, math
# Import from my files
import info/information.py
x = 1
while x < 10000:
    x += 1
info/information.quit("It took {} seconds for python to count to 10000")

In information.py:

import sys, time
start = time.time()

def quit(txt: str="Finished code with runtime {} seconds"):
    if "{" in txt and "}" in txt:
        try:
            print(txt.format(round(time.time() - start, 1)))
            sys.exit()
        except KeyError:
            raise KeyError("Please put nothing inbetween the \"{\" and the \"}\"")
    else:
        raise SyntaxError("Need to include \"{}\"!")

My error:

File "d:/Entertainment/Coding/Python/Pygame/BUG WORLD/main.py", line 6
    import modules/information
                  ^
SyntaxError: invalid syntax

I need help with this. Thanks in advance

Upvotes: 0

Views: 97

Answers (3)

Rachit Tayal
Rachit Tayal

Reputation: 1292

To manage imports in my project, I usually follow the below approach:

main.py
info
|----- information.py
|----- __init__.py

contents of __init__.py:

from . import information
#other module import if present

Code for information.py remains unchanged:

import sys, time
start = time.time()

def quit(txt: str="Finished code with runtime {} seconds"):
    if "{" in txt and "}" in txt:
        try:
            print(txt.format(round(time.time() - start, 1)))
            sys.exit()
        except KeyError:
            raise KeyError("Please put nothing inbetween the \"{\" and the \"}\"")
    else:
        raise SyntaxError("Need to include \"{}\"!")

Then you can import your modules in main.py like this:

import info
# info.information is accessible
# info.information.quit()
...

It might be a overdo for this case, since you have a single module but helps as your project size grows.

Upvotes: 2

Pr0digy
Pr0digy

Reputation: 29

You should try it like that.

# Imports
import random, math
# Import from my files
from info.information import quit
x = 1
while x < 10000:
    x += 1
quit("It took {} seconds for python to count to 10000")

Please notice you can also add the folder to your PYTHONPATH environment variable

sys.path.append('/full/path/to/application/app/folder')

Upvotes: 0

Reni Dantas
Reni Dantas

Reputation: 127

You should use import info.information, to acess directory info and then import module information.

Upvotes: 0

Related Questions