最近我一直在制作python项目,但是我的文件太乱了,所以我决定将文件分组到文件夹中。但是,我现在正努力从另一个目录/文件夹导入文件
我的代码:
# 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 \"{}\"!")
我的错误:
File "d:/Entertainment/Coding/Python/Pygame/BUG WORLD/main.py", line 6
import modules/information
^
SyntaxError: invalid syntax
我需要帮助。预先感谢
答案 0 :(得分:2)
要在我的项目中管理导入,我通常采用以下方法:
main.py
info
|----- information.py
|----- __init__.py
__init__.py
的内容:
from . import information
#other module import if present
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 \"{}\"!")
然后,您可以像这样将模块导入main.py
:
import info
# info.information is accessible
# info.information.quit()
...
在这种情况下,这可能是一个过大的问题,因为您只有一个模块,但是随着项目规模的增加会有所帮助。
答案 1 :(得分:0)
您应该使用import info.information进入目录 info ,然后导入模块信息。
答案 2 :(得分:0)
您应该这样尝试。
600..
请注意,您也可以将文件夹添加到PYTHONPATH环境变量中
# 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")