我用python编写了一个简单的程序。但是在一行中,它应该打开一个位于exe程序的同一文件夹中的.txt文件,不幸的是它没有找到它!在
这是我的代码:
from tkinter import *
def evaluate(event):
textfile = open('nomi.txt', 'r')
nomi = textfile.read().split(' ')
nome = str(entry.get())
indice = [0, 1, 2, 3, 4, 5, 6]
for x in indice:
if nomi[x] == nome:
if nomi[x]!=nomi[-1]:
nome2 = nomi[x+1]
else:
nome2 = nomi[0]
res.configure(text = "dovrai fare un regalo a " + nome2)
w = Tk()
Label(w, text="Il tuo nome:").pack()
entry = Entry(w)
entry.bind("<Return>", evaluate)
entry.pack()
res = Label(w)
res.pack()
w.mainloop()
我需要把这个.exe发送给其他人,我想把.txt文件和.exe文件放在.zip文件中…但是我需要它来读取.txt文件!在
open('nomi.txt', 'r')
将尝试打开当前工作目录中的文件。在这意味着您的
.txt
文件需要位于您正在使用的同一文件夹中。请注意,这可能与实际脚本的位置不同,这与这里无关。在我用askopenfilename手动选择我需要的文件来修复它!在
所以我的代码看起来是这样的,而且它可以工作:
打开文件时,需要指定文件所在的文件夹。如果您不能直接在代码中包含该文件夹,那么您还没有为我提供足够的信息来建议如何确定该文件夹的路径。在
相关问题 更多 >
编程相关推荐