How does the file.seek() work ?

Tim Chase python.list at tim.thechases.com
Mon Aug 24 21:37:00 CEST 2009


> I want the file pointer set to 100 and overwrite everything from there
[snip]
> def application(environ, response):
>     query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp')
>     range=environ.get('HTTP_RANGE','bytes=0-').replace
> ('bytes=','').split(',')
>     offset=[]
>     for r in range: offset.append(r.split('-'))
>     with open(query,'w+') as f:
>          f.seek(int(offset[0][0]))
>          while True:
>              chunk=environ['wsgi.input'].read(8192).decode('latin1')
>              if not chunk: break
>              f.write(chunk)
>     f=open(query)
>     l=str(os.fstat(f.fileno()).st_size)
>     response('200 OK', [('Content-Type', 'text/plain'), ('Content-
> Length', str(len(l)))])
>     return [l]

A couple items of note:

- you don't open the file in binary mode -- seek is more reliable 
in binary mode :)

- if you want to lop off the rest of the file, use f.truncate()

An example:

# create the initial file
 >>> f = file('zzz.zzz', 'wb+')
 >>> f.write('abcdefghijklmnop')
 >>> f.close()

 >>> f = file('zzz.zzz', 'ab+')
 >>> f.read() # show the existing content
'abcdefghijklmnop'
 >>> f.seek(5) # seek to the desired offset
 >>> f.truncate() # throw away everything after here
 >>> f.write('zyx') # write the new data at pos=5
 >>> f.close()

# demonstrate that it worked
 >>> f = file('zzz.zzz', 'rb')
 >>> f.read()
'abcdezyx'
 >>> f.close()

> also why must I open the file a second time to know how big it is ?

Likely the output has been buffered.  You can try using

   f.flush() # write all the data to the disk first
   size = os.fstat(f.fileno()).st_size

which seems to do the trick for me.

-tkc











More information about the Python-list mailing list