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

我使用 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')


德玛西亚99
浏览 127回答 1
1回答

凤凰求蛊

我认为你的问题就在这里:export_dir + str(MRBTS) +'_IPV6.xml'askdirectory()不包括尾部斜杠。你真正想要的是:f'{export_dir}\{MRBTS}_IPV6.xml'然而,更清洁的方法如下所示:from tkinter import Tk, filedialogfrom os import pathroot = Tk()root.geometry('800x600')root.title("Test")&nbsp; &nbsp;#with one function handling all the save logic#~it becomes harder to make mistakes and easier to find themdef save_utf8(filename, data):&nbsp; &nbsp; folder&nbsp; &nbsp;= filedialog.askdirectory()&nbsp; &nbsp; filepath = path.join(folder, filename)&nbsp; &nbsp; with open(filepath, 'wb') as f:&nbsp; &nbsp; &nbsp; &nbsp; f.write(data.encode('utf-8'))&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;#represents some data that your app concoctedMRBTS&nbsp; &nbsp;= 'blahblah'xmldata = '<blah>BLAH</blah><blah>BLAH</blah><blah>BLAH</blah>'#utilize the save functionsave_utf8(f'{MRBTS}_IPV6.xml', xmldata)root.mainloop()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python