def doExport(self, event):
dlg = wx.FileDialog(self, "Save to file:", ".", "", "Text (*.txt)|*.txt", wx.SAVE|wx.OVERWRITE_PROMPT)
if dlg.ShowModal() == wx.ID_OK:
i = dlg.GetFilterIndex()
if i == 0: # Text format
try:
f = open(dlg.GetPath(), "w")
f.write("# Date, From, SerivceCenter, Message\n")
for i in self.itemDataMap.keys():
entry = self.itemDataMap[i]
f.write('%s,%s,%s,%s\n' % (entry[1], entry[2], entry[4].smsc, entry[3]))
f.close()
pySIMmessage(self, "SMS export to file was successful\n\nFilename: %s" % dlg.GetPath(), "Export OK")
except:
pySIMmessage(self, "Unable to save your SMS messages to file: %s" % dlg.GetPath(), "Export error")
#print_exc()
dlg.Destroy()
python类SAVE的实例源码
def captureImage(self, event=None):
## Parts borrowed from backends_wx.py from matplotlib
# Fetch the required filename and file type.
filetypes, exts, filter_index = self.canvas._get_imagesave_wildcards()
default_file = self.canvas.get_default_filename()
dlg = wx.FileDialog(self, "Save to file", "", default_file,
filetypes,
wx.SAVE|wx.OVERWRITE_PROMPT)
dlg.SetFilterIndex(filter_index)
if dlg.ShowModal() == wx.ID_OK:
dirname = dlg.GetDirectory()
filename = dlg.GetFilename()
format = exts[dlg.GetFilterIndex()]
basename, ext = os.path.splitext(filename)
if ext.startswith('.'):
ext = ext[1:]
if ext in ('svg', 'pdf', 'ps', 'eps', 'png') and format!=ext:
#looks like they forgot to set the image type drop
#down, going with the extension.
format = ext
self.canvas.print_figure(
os.path.join(dirname, filename), format=format)
def OnGenerateProgramMenu(self, event):
dialog = wx.FileDialog(self, _("Choose a file"), os.getcwd(), self.Controler.GetProgramFilePath(), _("ST files (*.st)|*.st|All files|*.*"), wx.SAVE | wx.CHANGE_DIR)
if dialog.ShowModal() == wx.ID_OK:
filepath = dialog.GetPath()
message_text = ""
header, icon = _("Done"), wx.ICON_INFORMATION
if os.path.isdir(os.path.dirname(filepath)):
program, errors, warnings = self.Controler.GenerateProgram(filepath)
message_text += "".join([_("warning: %s\n") % warning for warning in warnings])
if len(errors) > 0:
message_text += "".join([_("error: %s\n") % error for error in errors])
message_text += _("Can't generate program to file %s!") % filepath
header, icon = _("Error"), wx.ICON_ERROR
else:
message_text += _("Program was successfully generated!")
else:
message_text += _("\"%s\" is not a valid folder!") % os.path.dirname(filepath)
header, icon = _("Error"), wx.ICON_ERROR
message = wx.MessageDialog(self, message_text, header, wx.OK | icon)
message.ShowModal()
message.Destroy()
dialog.Destroy()
def doExport(self, event):
export_count = 0
dlg = wx.FileDialog(self, "Save to file:", ".", "", "Text (*.txt)|*.txt", wx.SAVE|wx.OVERWRITE_PROMPT)
if dlg.ShowModal() == wx.ID_OK:
i = dlg.GetFilterIndex()
if i == 0: # Text format
try:
f = open(dlg.GetPath(), "w")
f.write('# "Name", Number\n')
for i in range(self.listCtrl.GetItemCount()):
f.write('"%s",%s\n' % (self.getColumnText(i,0), self.getColumnText(i,1)))
export_count += 1
f.close()
pySIMmessage(self, "Exported %d phonebook contacts\n\nFilename: %s" % (export_count, dlg.GetPath()), "Export OK")
except:
print_exc()
pySIMmessage(self, "Unable to save your phonebook to file: %s" % dlg.GetPath(), "Export error")
# elif i == 1: # Excel document
# try:
# xl = win32com.client.Dispatch("Excel.Application")
# xl.Workbooks.Add()
# xl.Cells(1,1).Value = "Name"
# xl.Cells(1,2).Value = "Number"
# for i in range(self.listCtrl.GetItemCount()):
# row = i + 2
# xl.Cells(row,1).Value = self.getColumnText(i,0)
# xl.Cells(row,2).Value = self.getColumnText(i,1)
# export_count += 1
# xl.ActiveWorkbook.SaveAs(dlg.GetPath())
# xl.ActiveWorkbook.DisplayAlerts = 0
# #xl.Saved = 1
# xl.Quit()
# pySIMmessage(self, "Exported %d phonebook contacts\n\nFilename: %s" % (export_count, dlg.GetPath()), "Export OK")
# except:
# print_exc()
# pySIMmessage(self, "Unable to save your phonebook to file: %s" % dlg.GetPath(), "Export error")
dlg.Destroy()
def doExport(self, event):
export_count = 0
dlg = wx.FileDialog(self, "Save to file:", ".", "", "Text (*.txt)|*.txt", wx.SAVE|wx.OVERWRITE_PROMPT)
if dlg.ShowModal() == wx.ID_OK:
i = dlg.GetFilterIndex()
if i == 0: # Text format
try:
f = open(dlg.GetPath(), "w")
f.write('# "Name", Number\n')
for i in range(self.listCtrl.GetItemCount()):
f.write('"%s",%s\n' % (self.getColumnText(i,0), self.getColumnText(i,1)))
export_count += 1
f.close()
pySIMmessage(self, "Exported %d phonebook contacts\n\nFilename: %s" % (export_count, dlg.GetPath()), "Export OK")
except:
print_exc()
pySIMmessage(self, "Unable to save your phonebook to file: %s" % dlg.GetPath(), "Export error")
# elif i == 1: # Excel document
# try:
# xl = win32com.client.Dispatch("Excel.Application")
# xl.Workbooks.Add()
# xl.Cells(1,1).Value = "Name"
# xl.Cells(1,2).Value = "Number"
# for i in range(self.listCtrl.GetItemCount()):
# row = i + 2
# xl.Cells(row,1).Value = self.getColumnText(i,0)
# xl.Cells(row,2).Value = self.getColumnText(i,1)
# export_count += 1
# xl.ActiveWorkbook.SaveAs(dlg.GetPath())
# xl.ActiveWorkbook.DisplayAlerts = 0
# #xl.Saved = 1
# xl.Quit()
# pySIMmessage(self, "Exported %d phonebook contacts\n\nFilename: %s" % (export_count, dlg.GetPath()), "Export OK")
# except:
# print_exc()
# pySIMmessage(self, "Unable to save your phonebook to file: %s" % dlg.GetPath(), "Export error")
dlg.Destroy()
def OnSave(self,e):
panelphase = self.GetChildren()[1].GetPage(0)
if panelphase.pipeline_started == False:
cwd = self.CurrentWD()
if IsNotWX4():
dlg = wx.FileDialog(self, "Choose a file", cwd, "", "fin files (*.fin)|*.fin|All files (*.*)|*.*", wx.SAVE | wx.OVERWRITE_PROMPT)
else:
dlg = wx.FileDialog(self, "Choose a file", cwd, "", "fin files (*.fin)|*.fin|All files (*.*)|*.*", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
if dlg.ShowModal() == wx.ID_OK:
self.filename=dlg.GetFilename()
self.dirname=dlg.GetDirectory()
SaveInstance(self)
dlg.Destroy()
def OnSaveMesh(self, evt):
dlg = wx.FileDialog(self, "Choose a file", ".", "", "*", wx.SAVE)
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetFilename()
dirname = dlg.GetDirectory()
filepath = os.path.join(dirname, filename)
self.glcanvas.mesh.saveFile(filepath, True)
self.glcanvas.Refresh()
dlg.Destroy()
return
def OnSaveScreenshot(self, evt):
dlg = wx.FileDialog(self, "Choose a file", ".", "", "*", wx.SAVE)
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetFilename()
dirname = dlg.GetDirectory()
filepath = os.path.join(dirname, filename)
saveImageGL(self.glcanvas, filepath)
dlg.Destroy()
return
def SaveProjectAs(self):
filepath = self.Controler.GetFilePath()
if filepath != "":
directory, filename = os.path.split(filepath)
else:
directory, filename = os.getcwd(), "%(projectName)s.xml" % self.Controler.GetProjectProperties()
dialog = wx.FileDialog(self, _("Choose a file"), directory, filename, _("PLCOpen files (*.xml)|*.xml|All files|*.*"), wx.SAVE | wx.OVERWRITE_PROMPT)
if dialog.ShowModal() == wx.ID_OK:
filepath = dialog.GetPath()
if os.path.isdir(os.path.dirname(filepath)):
result = self.Controler.SaveXMLFile(filepath)
if not result:
self.ShowErrorMessage(_("Can't save project to file %s!") % filepath)
else:
self.ShowErrorMessage(_("\"%s\" is not a valid folder!") % os.path.dirname(filepath))
self._Refresh(TITLE, FILEMENU, PAGETITLES)
dialog.Destroy()
def _ExportSlave(self):
dialog = wx.FileDialog(self.GetCTRoot().AppFrame,
_("Choose a file"),
os.path.expanduser("~"),
"%s.eds" % self.CTNName(),
_("EDS files (*.eds)|*.eds|All files|*.*"),
wx.SAVE | wx.OVERWRITE_PROMPT)
if dialog.ShowModal() == wx.ID_OK:
result = eds_utils.GenerateEDSFile(dialog.GetPath(), self.GetCurrentNodeCopy())
if result:
self.GetCTRoot().logger.write_error(_("Error: Export slave failed\n"))
dialog.Destroy()
def on_export_db(self, event): # wxGlade: admin_dash.<event_handler>
import time
mytime=time.localtime()# returns year, month,date,etc
filename="Full_DB_"+str(mytime[2])+"_"+str(mytime[1])+"_"+str(mytime[0])
wcd="Exam Files(*.xam)|*.xam|"
dir = "/home"
save_dlg = wx.FileDialog(self, message='Save file as...', defaultDir=dir, defaultFile= filename, wildcard=wcd, style=wx.SAVE | wx.OVERWRITE_PROMPT)
if save_dlg.ShowModal() == wx.ID_OK:
path = save_dlg.GetPath()
try:
self.DB.export(path+".xam")
dlg = wx.MessageDialog(self, 'Successfully Exported', '',wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
except:
dlg = wx.MessageDialog(self, 'Error Exporting file\n' )
dlg.ShowModal()
save_dlg.Destroy()
self.label_export.SetForegroundColour(self.label_fg_color)
event.Skip()
def save(self):
filename="custom_report.xls"
path=''
wcd="Excel Files(*.xls)|*.xls|"
dir = "/home"
save_dlg = wx.FileDialog(None, message='Save file as...', defaultDir=dir, defaultFile= filename, wildcard=wcd, style=wx.SAVE | wx.OVERWRITE_PROMPT)
if save_dlg.ShowModal() == wx.ID_OK:
path = save_dlg.GetPath()
self.book.save( path)
subprocess.call(["xdg-open",path])
def OnSaveScreenshot(self, evt):
dlg = wx.FileDialog(self, "Choose a file", ".", "", "*", wx.SAVE)
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetFilename()
dirname = dlg.GetDirectory()
filepath = os.path.join(dirname, filename)
saveImageGL(self.glcanvas, filepath)
dlg.Destroy()
return
def OnSaveMesh(self, evt):
dlg = wx.FileDialog(self, "Choose a file", ".", "", "*", wx.SAVE)
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetFilename()
dirname = dlg.GetDirectory()
filepath = os.path.join(dirname, filename)
self.glcanvas.mesh.saveFile(filepath, True)
self.glcanvas.Refresh()
dlg.Destroy()
return
def OnSaveScreenshot(self, evt):
dlg = wx.FileDialog(self, "Choose a file", ".", "", "*", wx.SAVE)
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetFilename()
dirname = dlg.GetDirectory()
filepath = os.path.join(dirname, filename)
saveImageGL(self.glcanvas, filepath)
dlg.Destroy()
return
def OnSaveAs(self, event): # wxGlade: TerminalFrame.<event_handler>
"""Save contents of output window."""
with wx.FileDialog(
None,
"Save Text As...",
".",
"",
"Text File|*.txt|All Files|*",
wx.SAVE) as dlg:
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPath()
with codecs.open(filename, 'w', encoding='utf-8') as f:
text = self.text_ctrl_output.GetValue().encode("utf-8")
f.write(text)
def OnSaveAs(self, event):
"""Save contents of output window."""
filename = None
dlg = wx.FileDialog(None, "Save Text As...", ".", "", "Text File|*.txt|All Files|*", wx.SAVE)
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPath()
dlg.Destroy()
if filename is not None:
f = file(filename, 'w')
text = self.text_ctrl_output.GetValue()
if type(text) == unicode:
text = text.encode("latin1") #hm, is that a good asumption?
f.write(text)
f.close()
def OnTBSave(self, event):
if self.data is None:
wx.MessageBox('Please record a spectrum first!', 'Save Spectrum', wx.OK | wx.ICON_INFORMATION)
return
if self.running:
rng = True
self.OnTBStart()
else:
rng = False
dlg = wx.FileDialog(None, "Save Spectrum", os.getcwd(), "", "*.*", wx.SAVE)
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPath()
# set new working directory
directory = os.path.split(filename)
if not os.path.isdir(filename):
os.chdir(directory[0])
# save file
np.savetxt(filename, np.transpose(np.array([self.wlAxis, self.data])))
# add to plot window
self.addLine(self.wlAxis, self.data)
dlg.Destroy()
if rng:
self.OnTBStart()
def OnSaveAs(self, evt):
dialog = wx.FileDialog(None, "Log File to Save to", defaultDir=".",
defaultFile="MQTT.log", style=wx.SAVE)
if dialog.ShowModal() == wx.ID_OK:
filename = dialog.GetPath()
dialog.Destroy()
file = open(filename, "w+")
sortedKeys = self.itemDataMap.keys()
sortedKeys.sort()
for i in sortedKeys:
curitem = self.itemDataMap[i]
file.write(curitem[1]+" "+curitem[2]+" "+curitem[3]+" "+curitem[4]+"\n\n")
file.close()
def SaveFile(self, fileName=''):
"""Saves the file to the type specified in the extension. If no file
name is specified a dialog box is provided. Returns True if sucessful,
otherwise False.
.bmp Save a Windows bitmap file.
.xbm Save an X bitmap file.
.xpm Save an XPM bitmap file.
.png Save a Portable Network Graphics file.
.jpg Save a Joint Photographic Experts Group file.
"""
extensions = {
"bmp": wx.BITMAP_TYPE_BMP, # Save a Windows bitmap file.
"xbm": wx.BITMAP_TYPE_XBM, # Save an X bitmap file.
"xpm": wx.BITMAP_TYPE_XPM, # Save an XPM bitmap file.
"jpg": wx.BITMAP_TYPE_JPEG, # Save a JPG file.
"png": wx.BITMAP_TYPE_PNG, # Save a PNG file.
}
fType = _string.lower(fileName[-3:])
dlg1 = None
while fType not in extensions:
if dlg1: # FileDialog exists: Check for extension
dlg2 = wx.MessageDialog(self, 'File name extension\n'
'must be one of\nbmp, xbm, xpm, png, or jpg',
'File Name Error', wx.OK | wx.ICON_ERROR)
try:
dlg2.ShowModal()
finally:
dlg2.Destroy()
# FileDialog doesn't exist: just check one
else:
dlg1 = wx.FileDialog(
self,
"Choose a file with extension bmp, gif, xbm, xpm, png, or jpg", ".", "",
"BMP files (*.bmp)|*.bmp|XBM files (*.xbm)|*.xbm|XPM file (*.xpm)|*.xpm|PNG files (*.png)|*.png|JPG files (*.jpg)|*.jpg",
wx.SAVE | wx.OVERWRITE_PROMPT
)
if dlg1.ShowModal() == wx.ID_OK:
fileName = dlg1.GetPath()
fType = _string.lower(fileName[-3:])
else: # exit without saving
dlg1.Destroy()
return False
if dlg1:
dlg1.Destroy()
# Save Bitmap
res = self._Buffer.SaveFile(fileName, extensions[fType])
return res
def on_import_db(self, event): # wxGlade: admin_dash.<event_handler>
'''
msg="This feature is suspended"
dlg = wx.MessageDialog(self, msg, '',wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
return 0
'''
msg="Importing may overwrite some of the existing data \n Do you want to continue?"
dlg = wx.MessageDialog(self, msg)#,wx.SAVE|wx.ICON_QUESTION)
if dlg.ShowModal() == wx.ID_OK:
dir = "/home"
wcd="Exam Files(*.xam)|*.xam|"
open_dlg = wx.FileDialog(self, message='Choose a file', defaultDir=dir, defaultFile='', wildcard=wcd, style=wx.OPEN|wx.CHANGE_DIR)
if open_dlg.ShowModal() == wx.ID_OK:
path = open_dlg.GetPath()
try:
self.DB.import_(path)
dlg = wx.MessageDialog(self, 'Successfully imported', '',wx.OK | wx.ICON_INFORMATION)
except:
dlg = wx.MessageDialog(self, 'Sorry, Could not import', '',wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
self.label_import_db.SetForegroundColour(self.label_fg_color)
event.Skip()
def onSaveAs ( self, evt=None ):
"""This method saves the file with a new name"""
# Create the dialog. In this case the current directory is forced as the starting
# directory for the dialog, and no default file name is forced. This can easilly
# be changed in your program. This is an 'save' dialog.
#
# Unlike the 'open dialog' example found elsewhere, this example does NOT
# force the current working directory to change if the user chooses a different
# directory than the one initially set.
dlg = wx.FileDialog(self,
message="Save file as ...",
defaultDir=os.getcwd(),
defaultFile="",
wildcard=wildcard,
style=wx.SAVE )
# This sets the default filter that the user will initially see. Otherwise,
# the first filter in the list will be used by default.
dlg.SetFilterIndex(2)
# Show the dialog and retrieve the user response. If it is the OK response,
# process the data.
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
print "In onSaveAs, the path is %s" % path
# Normally, at this point you would save your data using the file and path
# data that the user provided to you, but since we didn't actually start
# with any data to work with, that would be difficult.
#
# The code to do so would be similar to this, assuming 'data' contains
# the data you want to save:
#
# fp = file(path, 'w') # Create file anew
# fp.write(data)
# fp.close()
#
# You might want to add some error checking :-)
else :
print "The file dialog was canceled before anything was selected"
# Note that the current working dir didn't change. This is good since
# that's the way we set it up.
# Destroy the dialog. Don't do this until you are done with it!
# BAD things can happen otherwise!
dlg.Destroy()
def onSaveAs ( self, evt=None ):
"""This method saves the file with a new name"""
# Create the dialog. In this case the current directory is forced as the starting
# directory for the dialog, and no default file name is forced. This can easilly
# be changed in your program. This is an 'save' dialog.
#
# Unlike the 'open dialog' example found elsewhere, this example does NOT
# force the current working directory to change if the user chooses a different
# directory than the one initially set.
dlg = wx.FileDialog(self,
message="Save file as ...",
defaultDir=os.getcwd(),
defaultFile="",
wildcard=wildcard,
style=wx.SAVE )
# This sets the default filter that the user will initially see. Otherwise,
# the first filter in the list will be used by default.
dlg.SetFilterIndex(2)
# Show the dialog and retrieve the user response. If it is the OK response,
# process the data.
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
print "In onSaveAs, the path is %s" % path
# Normally, at this point you would save your data using the file and path
# data that the user provided to you, but since we didn't actually start
# with any data to work with, that would be difficult.
#
# The code to do so would be similar to this, assuming 'data' contains
# the data you want to save:
#
# fp = file(path, 'w') # Create file anew
# fp.write(data)
# fp.close()
#
# You might want to add some error checking :-)
else :
print "The file dialog was canceled before anything was selected"
# Note that the current working dir didn't change. This is good since
# that's the way we set it up.
# Destroy the dialog. Don't do this until you are done with it!
# BAD things can happen otherwise!
dlg.Destroy()
def onSaveAs ( self, evt=None ):
"""This method saves the file with a new name"""
# Create the dialog. In this case the current directory is forced as the starting
# directory for the dialog, and no default file name is forced. This can easilly
# be changed in your program. This is an 'save' dialog.
#
# Unlike the 'open dialog' example found elsewhere, this example does NOT
# force the current working directory to change if the user chooses a different
# directory than the one initially set.
dlg = wx.FileDialog(self,
message="Save file as ...",
defaultDir=os.getcwd(),
defaultFile="",
wildcard=wildcard,
style=wx.SAVE )
# This sets the default filter that the user will initially see. Otherwise,
# the first filter in the list will be used by default.
dlg.SetFilterIndex(2)
# Show the dialog and retrieve the user response. If it is the OK response,
# process the data.
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
print "In onSaveAs, the path is %s" % path
# Normally, at this point you would save your data using the file and path
# data that the user provided to you, but since we didn't actually start
# with any data to work with, that would be difficult.
#
# The code to do so would be similar to this, assuming 'data' contains
# the data you want to save:
#
# fp = file(path, 'w') # Create file anew
# fp.write(data)
# fp.close()
#
# You might want to add some error checking :-)
else :
print "The file dialog was canceled before anything was selected"
# Note that the current working dir didn't change. This is good since
# that's the way we set it up.
# Destroy the dialog. Don't do this until you are done with it!
# BAD things can happen otherwise!
dlg.Destroy()
def onSaveAs ( self, evt=None ):
"""This method creates a new file"""
# Create the dialog. In this case the current directory is forced as the starting
# directory for the dialog, and no default file name is forced. This can easilly
# be changed in your program. This is an 'save' dialog.
#
# Unlike the 'open dialog' example found elsewhere, this example does NOT
# force the current working directory to change if the user chooses a different
# directory than the one initially set.
dlg = wx.FileDialog(self,
message="Save file as ...",
defaultDir=os.getcwd(),
defaultFile="",
wildcard=wildcard,
style=wx.SAVE )
# This sets the default filter that the user will initially see. Otherwise,
# the first filter in the list will be used by default.
dlg.SetFilterIndex(2)
# Show the dialog and retrieve the user response. If it is the OK response,
# process the data.
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
print "In onNew, the path is %s" % path
# Normally, at this point you would save your data using the file and path
# data that the user provided to you, but since we didn't actually start
# with any data to work with, that would be difficult.
#
# The code to do so would be similar to this, assuming 'data' contains
# the data you want to save:
#
# fp = file(path, 'w') # Create file anew
# fp.write(data)
# fp.close()
#
# You might want to add some error checking :-)
#
else :
print "The file dialog was canceled before anything was selected"
# Note that the current working dir didn't change. This is good since
# that's the way we set it up.
# Destroy the dialog. Don't do this until you are done with it!
# BAD things can happen otherwise!
dlg.Destroy()