python - 无法在 .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')
解决方案
我认为你的问题就在这里:
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()
推荐阅读
- javascript - 在 reactJS 中触发 onClick 函数后如何进入初始状态?
- regex - 是否有从 Google 表格中的框中提取特定字符的公式?
- angular - 谷歌图表:在柱形图中显示轴的末端或轴的顶部
- node.js - How to click an element with Selenium webdriver javascript?
- java - 跟踪位置以动画片段之间的过渡
- python - 如何制作文本文件并将数据(str和int)放入python?
- android - 如何更改时间选择器的时钟图像
- c# - 如何在不使用 Base64 的情况下将数字加密/解密为字符串
- asp.net - 无需下载即可在服务器上调整图像大小
- excel - Search for a string in a pdf file then copy the info into word/excel/txt file?