Best way to create temporary file?

Frank Millman frank at chagford.com
Fri Apr 29 07:11:50 EDT 2005


Hi all

I need to generate potentially large reports from a database, and I
want to offer the option of print preview before actually printing
(using wxPython). I figure that the best way to achieve this is to
write the report to a temporary file, or more likely to a temporary
directory with a separate file for each page. I can use that for
previewing and for printing, and then delete the file/directory.

There seems to be a few ways to achieve this, and I am not sure of the
best way.

1. I can call tempfile.TemporaryFile() for each file required.

2. I can call tempfile.mkdtemp() to create a temporary directory, and
create each file manually.

3. I can call os.tmpfile() for each file required.

After creating the files, I need to re-read them, either one at a time
in sequence (if printing), or any one at random (if previewing a
particular page). This makes me lean towards method 2.

With this method, I create the files manually, so I can name them
according to their page numbers, which makes it easy to open and close
them as required. The other two methods return open file objects, so
it seems that I cannot close them, as there would be no means of
accessing their contents subsequently. Therefore I would have to
maintain a list of open file objects, use indexing to retrieve a
particular page, and then perform seek(0) before I could read it. A
slight downside of method 2 is that I have to delete the files and the
directory manually when I have finished.

I have two additional questions regarding method 3.

Firstly, I am not sure how it works. The docs say that the file has no
directory entries associated with it, and it will be automatically
deleted when there are no file descriptors for the file. What does
this mean? Does it create a physical file, or is it stored in memory?
If the latter, could I run into memory problems if I create a report
with hundreds of pages?

Secondly, I can create the file using FC3 (Python 2.4), but if I try
on Windows 2000 (Python 2.4) I get the message 'OSError: Permission
denied', even though I am a member of the Administrators group.

Any advice on the best approach for this will be much appreciated.

Frank Millman



More information about the Python-list mailing list