在.exe程序中打开.txt文件

时间:2018-10-18 11:26:02

标签: python

我用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文件!

3 个答案:

答案 0 :(得分:3)

open('nomi.txt', 'r')将尝试在您的当前工作目录中打开文件。

这意味着您的.txt文件需要与工作所在的文件夹相同。请注意,这可能与实际脚本的位置有所不同,此处与此无关。

答案 1 :(得分:1)

我通过使用askopenfilename手动选择了我需要的文件来修复它!

所以我的代码现在看起来像这样,并且可以正常工作:

from tkinter import *
from tkinter import filedialog

def evaluate(event):
    nome = str(entry.get())
    indice = [0, 1, 2, 3, 4, 5, 6]
    for x in indice:
        print(nomi[x])
        print(nome)
        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)

root = Tk()
root.filename =  filedialog.askopenfilename(initialdir = "/",title = "Select 
file",filetypes = (("txt","*.txt"),("all files","*.*")))
textfile = open(root.filename, 'r')
nomi = textfile.read().split(' ')

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()

答案 2 :(得分:0)

打开文件时,需要指定文件所在的文件夹。如果您不能仅将其直接包含在代码中,则您没有为我提供足够的信息来建议如何确定该文件夹的路径。