problems using pythom tempfile module

S

samir.vds

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
 
B

buffi

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.
 
S

samir.vds

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?
 
S

Steve Holden

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
 
B

buffi

Pretend that you have a number that is always pointing somewhere in
your temporary file.
It starts a 0.
If you then write "lalalala" (8 characters) it will point after these
at position 8, so that you can write more stuff after your previous
text later by calling write.

The read method reads all the data from the current position of the
"pointer" to the end of the file. If you simply call it after writing,
you wont get anything since you are already at the end of the file.
Therefore you "rewind" the pointer back to the start by calling seek
which takes the position in the file to go to...
your_file.seek(0) returns you to the start of the file to read all of
its data

- Björn Kempén
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top