Teoman Yüksel Teoman Yüksel - 3 months ago 9
Python Question

How to seperate a python file to couple files, making a real game with files

I made a little game with python/pygame. It's in one folder and it's 300+ lines. I want to develop this little game. I'm seeing lots of games
made by pygame, and I'm seeing they have folders like

main.py
,
classes.py
and
setup.py
.

But I only know the python language and a little pygame. How can I do the file things, or how can I learn?

Answer

To import a file called script.py from the same directory as your main file:

import script

To import a file called script.py from a sub directory called app:

import sys
sys.path.insert('app')
import script

To import a file called script.py from the parent directory:

import sys
import os
sys.path.insert(0, os.path.abspath('../'))
import script

To import a file called script.py from a sibling directory called app:

import sys
import os
sys.path.insert(0, os.path.abspath('../app'))
import script

The methods described above are fine if you need to quickly import a few files, but it is commonly recommended that people use virtualenv when handling larger projects.