为了账号安全,请及时绑定邮箱和手机立即绑定

无法在 .write 函数中提供动态名称

无法在 .write 函数中提供动态名称

德玛西亚99 2023-06-27 14:16:40
我使用 ttinker 给出导出文件的路径,然后尝试为输出文件提供动态名称,MRBTS 是一个不断变化的变量问题是有时我能够将文件保存在给定目录中,但文件名会自动更改为目录名,我认为已使用的 filedialog.askdirectory() 中存在问题,有人可以指导吗?Regen.configure(bg="grey")Regen.geometry("300x300+500+200")mylabel1=Label(text="VIL Regen Tool",fg="orange",bg="grey",font="Times 15 bold").pack()mylabel1=Label(text="Developed by Sushanto Banerjee",fg="orange",bg="grey",font="Times 15 bold").place(x=10,y=100)def xml_import():    global xml_file    xml_file=filedialog.askopenfile(filetypes=[("XML files","*.xml")])    label1=Label(text="XML Backup Imported").place(x=100,y=240)def excel_import():    global excel_file    excel_file=filedialog.askopenfilename(filetypes=[("Excel files","*.xlsx")])    label2=Label(text="IP Plan Imported").place(x=120,y=270)def export():    global export_dir    export_dir=filedialog.askdirectory()    a=filedialog.    mess=messagebox.showinfo(title="XML Generated",message="XMl generated")    command=Regen.destroy()    button=Button(text="Import XML Backup",width=30,command=xml_import).pack()button=Button(text="Import Excel IP Plan",width=30,command=excel_import).pack()button=Button(text="Generate",width=30,command=export).pack()Regen.mainloop()                mytree.write( export_dir + str(MRBTS) +'_IPV6.xml',encoding='UTF-8')
查看完整描述

1 回答

?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

我认为你的问题就在这里:

export_dir + str(MRBTS) +'_IPV6.xml'

askdirectory()不包括尾部斜杠。你真正想要的是:

f'{export_dir}\{MRBTS}_IPV6.xml'

然而,更清洁的方法如下所示:

from tkinter import Tk, filedialog

from os import path


root = Tk()

root.geometry('800x600')

root.title("Test")

   


#with one function handling all the save logic

#~it becomes harder to make mistakes and easier to find them

def save_utf8(filename, data):

    folder   = filedialog.askdirectory()

    filepath = path.join(folder, filename)

    with open(filepath, 'wb') as f:

        f.write(data.encode('utf-8'))


        

#represents some data that your app concocted

MRBTS   = 'blahblah'

xmldata = '<blah>BLAH</blah><blah>BLAH</blah><blah>BLAH</blah>'



#utilize the save function

save_utf8(f'{MRBTS}_IPV6.xml', xmldata)



root.mainloop()


查看完整回答
反对 回复 2023-06-27
  • 1 回答
  • 0 关注
  • 124 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信