我想在 kivy 中打开一些游戏文件(说明,关于信息...),所以我不必在 main.py 中输入所有内容,但使用这两种方法会给我一个错误。
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()
他们都给了我相同的 FileNotFoundError。我已经检查了至少五次,文件就在那里。
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'
尝试,除了部分只是因为我在尝试读取文件后正在编写代码。
我使用的方法错了吗?我尝试在任何类之外编写它们,但它给了我同样的错误,因此我将其返回到 MenuScreen 类中。
最佳答案
听起来您希望工作目录与脚本所在的目录相同。这是我用来跟踪相对路径的技术(默认情况下恢复到调用路径)。
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()
这样,您只需将脚本和文本文件放在同一目录中,而它们确切存储在文件系统中的位置或从何处调用程序并不重要。
关于python - 从同一目录打开 .txt 文件无法找到该文件(FileNotFoundError) - python/kivy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31377499/