PyExcelerator: How does one close a file?

John Machin sjmachin at lexicon.net
Tue May 9 19:02:15 EDT 2006


On 10/05/2006 7:57 AM, tkpmep at hotmail.com wrote:
> I use PyExcelerator to write data into Excel files, and repeatedly call
> the function writeData with different filenames fn from my main
> routine. Unfortunately, only one file - the last one - is created. The
> problem seems to lie with the fact that I do not close the existing
> file before calling the function again,

If you needed to close a file that was opened in another module, that 
would be a very peculiar API design. You don't need to.

> and the existing file is
> therefore just saved with a new name.

Your function creates a new instance of the Workbook class, as it 
should. The instance is abandoned when your function exits. One would 
not expect any carry-over between instances.

  Is there a way to close a
> PyExcelerator Excel file so that each call to the function results in a
> new file? There is no close() method as far as I can tell.
> 
> def writeData(fn, Data):
>     """Write the data into an Excel file named fn using PyExcelerator
>         Data is a list of real numbers"""
>     w=PyExcelerator.Workbook()

Last time I looked, the name was pyExcelerator -- that's a lower-case 
"p" at the front. How come you didn't get an exception here (or on 
earlier import)? Have you posted the actual code you executed???

>     ws = w.add_sheet("Sheet1")
>     for i in range(len(Data)):
>         ws.write(i, 0, Data[i])
>     w.save(fn)
> 

pyExcelerator is open-source; you should read it. According to my 
reading of the version 0.6.3 source (which version are you using?), the 
Workbook.save method calls the CompoundDoc.save method, which opens a 
physical file with the supplied name, writes to it, and closes it. 
AFAICT, there is no hint of anything that could cause the symptoms you 
describe.

I did a quick test using the following code and your function (with 
appropriate module name) on version 0.6.3. It worked as expected (Python 
2.4.3 on Windows XP). Which Python version are you using? What OS?

for k in range(3):
     writeData("zzz%d.xls" % k, range(k, k+10))

Perhaps the problem is closer to home; try inserting
print repr(fn)
before each call to your function, and
os.system("ls -l " + fn) # or "dir " + fn, or whatever it takes
after each call.

HTH,
John



More information about the Python-list mailing list