首页 > 解决方案 > 无法在 .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')

标签: pythonxmltkinter

解决方案


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

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

推荐阅读