Nona Urbiz
Nona Urbiz

Reputation: 5013

Python file.write() taking two tries?

not sure how to explain this, any help will be appreciated!

Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib2, pynotify, tempfile, os
>>> opener = urllib2.build_opener()
>>> page = opener.open('http://img.youtube.com/vi/RLGJU_xUVTs/1.jpg')
>>> thumb = page.read()
>>> temp = tempfile.NamedTemporaryFile(suffix='.jpg')
>>> temp.write(thumb)
>>> os.path.getsize(temp.name)
0
>>> temp.write(thumb)
>>> os.path.getsize(temp.name)
4096

thanks!

Upvotes: 2

Views: 393

Answers (2)

aaronasterling
aaronasterling

Reputation: 71004

If you open the thumb file, you'll see that there's one whole copy and a partial copy of the data that you are writing in it.

flush the file instead of writing a second time.

temp.flush()

The file wasn't writing the first time because the contents aren't large enough to fill the buffer. The second write overfills the buffer and so a buffer's worth of data gets written.

As Cameron points out in his answer, the buffer is automatically flushed when you close the file. If you want to keep it open for some reason (and the fact that this is an issue for you seems to indicate that you do), then you can call flush and the data will be written right away.

Upvotes: 10

Cameron
Cameron

Reputation: 98746

You haven't called flush() or close() on the file object before checking its size on disk -- there is an internal buffer that is automatically flushed only after a certain amount of data is written (this avoids too many expensive trips to the disk when doing many writes).

Upvotes: 2

Related Questions