0

I'm creating Hangman game using classes that are in separate files. One of them (wordsHangman.py)is responsible for randomly selecting a word from text file, and it's in a package "words_from_file". Later on I'm importing this module to another file containing class with the main game (hangman.py). However it's in a different folder.

Please see visual explanation -> https://i.stack.imgur.com/eZBJv.png

So far I tried with os module and adding

open(os.path.dirname("words.txt"), "r")

However it raises FileNotFoundError: [Errno 2] No such file or directory: ''

Currently I'm pointing path of package containing text file in wordsHangman.py in the following way :

file = open('words_from_file/words.txt', 'r')

init file in my words_from_file package contains :

from .wordsHangman import Words
__all__ = ["Words"]   

I'm importing wordsHangman module to hangman with :

from words_from_file import *

I would like to be able to import this module without 'manually' specifying file's path (so if it will be moved to another package, my hangman module will still be able to import it).

How can I do this ?

Mateusz
  • 1
  • 2
  • 2
    I'm not sure I'm following. Are you asking about reading the `txt` file or importing a module? – DeepSpace Aug 10 '19 at 17:03
  • possible answer : https://stackoverflow.com/questions/37516579/importing-user-defined-modules-in-python-from-a-directory and https://stackoverflow.com/questions/10161568/import-python-module-not-on-path . Also, look into this. you may not want to directly insert into `sys.path`. So , https://stackoverflow.com/questions/43476403/importerror-no-module-named-something – Tanmaya Meher Aug 10 '19 at 17:35
  • Sorry, I'm a bit chaotic as it's still new and not so clear for me. I would like to open the file without pointing at it's directory strictly as I'm doing now (words_from_file/word.txt). I'm searching for more dynamic way ensuring that python is going to find the file even if it will be moved to another folder. – Mateusz Aug 10 '19 at 17:52

0 Answers0