Reputation: 791
I want to open a few files for game in kivy (instructions, about info...), so I don't have to have everything typed in the main.py but using those two methods it gives me an error.
class MenuScreen(Screen):
try:
#os.path.dirname(sys.argv[0])
#fullpath = os.path.join(os.path.dirname(sys.argv[0]), 'navodila.txt')
#instructions = StringProperty("")
#with open(fullpath, "r") as inst:
# for line in inst:
# instructions += line
instructions = ""
with open("navodila.txt", "r") as file:
for line in file:
instructions += line
except: instructions = "Instructions failed to load."
def show_popup_inst(self):
p = InstructionsPopup(content=Label(text=self.instructions, text_size=self.size))
p.open()
They both give me the same FileNotFoundError. I've checked at least five times and the file is there.
Traceback (most recent call last):
File "C:\Users\Lara\Desktop\KIVY\LARA\Snaky Game\SNAKY REAL\SnakyGame4.py", line 361, in <module>
class MenuScreen(Screen):
File "C:\Users\Lara\Desktop\KIVY\LARA\Snaky Game\SNAKY REAL\SnakyGame4.py", line 371, in MenuScreen
with open("navodila.txt", "r") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'navodila.txt'
The try, except part is there just because I was working on code after trying reading a file.
Am I using the methods wrong? I've tried writing both of them outside any of the classes but it gave me the same error so I returned it inside in MenuScreen class.
Upvotes: 1
Views: 806
Reputation: 4658
It sounds like you want the working directory to be the same as the directory where the script lives. Here's a technique I use to keep track of relative paths (which revert to the calling path by default).
import os
script_path = os.path.dirname(os.path.realpath(__file__))
with open( os.path.join(script_path,"navodila.txt") , "r") as f:
do_stuff()
This way you just need to have the script and text file in the same directory and it doesn't matter where exactly they are stored in your filesystem or where you are calling the program from.
Upvotes: 1