1

I'm rather new to the Python language, but I have experience in several programming languages several being C++ and Java. I recently started learning Python because my school requires in our Computer Science class. Now I've used those programming languages extensively and some of the things in which Python does seems very odd.

I'll give you an example, firstly I can't import files from another directory. At the moment, I am trying to create a text-based RPG game. My idea was to have a entity superclass with the properties and then branch that off to other subclasses (player.. bosses.. enemies). I'd also thought I'll use for weapons and other items.

However, I recently discovered that by default you can't import files from other directories. I'm used to in Java and other languages that you being able to import files from anywhere you wanted. If that's the case then does every python file that's going to be used by another file have to be in the same directory? If that's the case then how do you organize the code? I assume there's a way, but I seem to be unable to find anything about it.

Community
  • 1
  • 1
Jaccob
  • 51
  • 1
  • 1
    possible duplicate of [Importing files from different folder in Python](http://stackoverflow.com/questions/4383571/importing-files-from-different-folder-in-python) – kdopen Apr 27 '15 at 15:04

1 Answers1

0

Certainly you can import a Python file from another directory.

Say, you've got the following structure.

/some/path
    |
    |
    `-script.py
    `-Test
        |
        |
        `-hello.py
        `-__init__.py

Then you can do the following in script.py

from Test import hello

hello.say_hello() # anything you want

Do notice the __init__.py. This is the 'magic' file that does the trick.

__init__.py can be empty if you want.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • Hm, I was under the impression that this was the case: http://stackoverflow.com/questions/4383571/importing-files-from-different-folder-in-python. – Jaccob Apr 27 '15 at 14:48
  • @Jaccob, that's the most common case described here. If you're having _severe_ problems with importing, then you'll have to 'play' with `PYTHONPATH`. BTW, why did you post your question if you found a dupe of it in a few minutes? :) – ForceBru Apr 27 '15 at 14:52