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.sstatic.net/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 ?

3
  • 2
    I'm not sure I'm following. Are you asking about reading the txt file or importing a module? Commented Aug 10, 2019 at 17:03
  • possible answer : stackoverflow.com/questions/37516579/… and stackoverflow.com/questions/10161568/… . Also, look into this. you may not want to directly insert into sys.path. So , stackoverflow.com/questions/43476403/… Commented Aug 10, 2019 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. Commented Aug 10, 2019 at 17:52

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.