problems using pythom tempfile module

Steve Holden steve at holdenweb.com
Sat Sep 15 18:40:22 EDT 2007


samir.vds at googlemail.com wrote:
> On Sep 15, 5:24 pm, buffi <bjorn.kem... at gmail.com> wrote:
>> On Sep 15, 11:11 pm, "samir.... at googlemail.com"
>>
>>
>>
>> <samir.... at googlemail.com> wrote:
>>> Hello everyone,
>>> I'm trying to test the tempfile module with the following script,
>>> which basically creates a temporary file, fills the file with some
>>> test data and prints it.
>>> import tempfile
>>> t = tempfile.TemporaryFile()
>>> t.write("lalalala")
>>> t.flush()
>>> print t.read()
>>> Unfortunately, the print statement gives me an empty string. Can
>>> somebody tell me what I'm doing wrong ?
>>> regards Samir
>> Do a t.seek(0) before you do the read to "rewind" the file and then it
>> should work.
> 
> Ok, this really worked. Can you elaborate why I have to insert this
> statement?
> 
Each file has a "current position". As you write a file the current 
position moves to stay just ahead of what's been written. So if you read 
it without resetting the current position (back to the beginning with 
seek(0)) you will get an immediate end of file (i.e. 0 bytes) returned.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline




More information about the Python-list mailing list