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

2024-09-29 22:10:45 发布

您现在位置: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文件!在


Tags: 文件text程序txtifresexepack
3条回答

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

这意味着您的.txt文件需要位于您正在使用的同一文件夹中。请注意,这可能与实际脚本的位置不同,这与这里无关。在

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

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

相关问题 更多 >

    热门问题