我需要保存文件并写入一个类。我有一些问题。
当文件被保存时,我总是会出错我不会做的事。我希望例外只有wenn necesarry,在这种情况下删除保存的文件。
使用我的代码我无法写入文本文件。我的函数SaveFile和Run在课堂上出现了什么问题?
class InterfaceApp(root):
def __init__(self,parent):
root.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
frInstrument = Tkinter.Frame(width=800, height=200, bg="",colormap="new")
frInstrument.grid(row=0,sticky='EW')
# Create a custom Menu
menu = Tkinter.Menu(self,tearoff = 0)
self.config(menu=menu)
filemenu = Tkinter.Menu(self,tearoff = 0)
menu.add_cascade(label='File',menu=filemenu)
filemenu.add_command(label='Create New File...', command = self.SaveFile())
def SaveFile(self):
self.dataname = asksaveasfile(mode='w', defaultextension='.txt')
self.datamode = "a"
try:
self.fout = open(self.dataname, self.datamode)
except Exception, e:
tkMessageBox.showerror("Error", str(e))
def Run(self):
self.keithleyPower = rm.open_resource(self.choiceVarPower.get())
self.keithleyMultimeter = rm.open_resource(self.choiceVarMulti.get())
self.t = datetime.datetime.now()
self.currdatetime = self.t.timetuple()
self.currutime = time.mktime(self.t.timetuple())
self.yr = str(self.currdatetime[0])
self.curr_date = "%02d"%int(self.yr[2:]) + "%02d"%self.currdatetime[1] + "%02d"%self.currdatetime[2]
self.curr_time = "%02d:"%self.currdatetime[3] + "%02d:"%self.currdatetime[4] + "%02d:"%self.currdatetime[5]
self.date_time = self.curr_date + " " + self.curr_time
self.fout.write(self.date_time+"\n")
if __name__ == '__main__':
app = InterfaceApp(None)
app.title("LED Monitoring: Voltage rise detection")
app.mainloop()
答案 0 :(得分:0)
必须修复函数SaveFile
。
def SaveFile(self):
self.file_opt = self.options = {}
self.options['filetypes'] = [('Text Files', '.txt')]
self.dataname = asksaveasfilename(**self.file_opt)
self.datamode = 'a'
try:
self.fout = open(self.dataname, self.datamode)
except Exception, e:
strError = "Output file open error: "+ str(e)
tkMessageBox.showerror("Error", strError)
您可以将数据写入文件。
self.fout.write("data")