George McCown wrote:
self.newlist re-patterned by a regex method:
OBJECTID,FULL_ADDRESS
8759,1006 CARDINAL PL
8724,1006 CANARY LN
17745,1005 WESTCHESTER DR
9774,1005 W WABASH AVE
Well, now, hold on. The code you showed us expects self.newlist to
contain a list of filenames (or filename glob patterns). Each of the
files in that list is then expected to contain comma-separated data,
like that. Are you saying that data above is what self.newlist
contains? If so, then your code is incorrect. You shouldn’t be using
glob.glob at all.
Actually, there’s a more important problem that I just noticed. You
have this:
f = StringIO(self.newlist)
print 'f is %s' % f.read()
for filename in glob.glob(f.read()):
That “print” statement is going to use up all of the data from the
list. When that’s done, “f” will be at end-of-file. Thus, the f.read()
in the next line will read nothing at all.
So, what, EXACTLY, is in self.newlist? Is it one file name? Is it
several file names? Is it the comma-separated data above? If you can
answer that, then we may be able to fix your code.
That is NOT Excel data, so you should not
pretend that you can create an .xls file.
Tim, please clarify this statement.
Well, look at what the code does. You call wx.FileDialog. If that
returns OK, then you fetch the filename and directory that the user
specified. You then create that file, and write the contents of
“self.newlist” to it. So, what you have written is NOT an Excel .xls
spreadsheet. It’s just plain text. If it really is comma-separated
data, then you could use the “.csv” extension (which Excel knows how to
open), but it’s definitely not a .xls file. .xls files are a special
binary format known only to Excel.
Now, you do have code later on that tries to create a genuine Excel .xls
files, but you’re not using the filename from the wx.FileDialog. You’re
using the filenames from self.newlist.
So, what were you really trying to do here? Were you trying to say "If
the user specified a .txt name, then save self.newlist in
comma-separated form. If the user specified a .xls name, then create an
Excel spreadsheet."? If that was your goal, then I think we can help
you do that, but it’s quite different from the code you have. Something
like this:
if dlg.ShowModal() == wx.ID_OK:
ext = os.path.splitext(dlg.GetFilename())[1]
if ext == '.txt':
# They asked for a .txt file.
f = open(dlg.GetPath(),'w')
f.write(self.newlist)
else:
# They asked for a .xls file.
f = StringIO(self.newlist)
wb = xlwt.Workbook()
sheet = wb.add_sheet('sheet 1')
reader = csv.reader(f, 'rb'), delimiter=',')
for rowx, row in enumerate(reader):
for colx, value in enumerate(row):
sheet.write(rowx, colx, value)
wb.save(dlg.GetPath())
print "Done"
–
Tim Roberts, ti...@probo.com
Providenza & Boekelheide, Inc.