Best way to write a file n-bytes long

Greg Brunet gregbrunet at NOSPAMsempersoft.com
Wed Aug 27 12:58:54 EDT 2003


"Michael Porter" <mporter at despammed.com> wrote in message
news:3f4c8ebc$0$256$cc9e4d1f at news.dial.pipex.com...
>
> "Tony C" <cappy2112 at yahoo.com> wrote in message
> news:8d3e714e.0308261404.12045d96 at posting.google.com...
> > Does Python have a function that is analogous to C's write() or
> > fwrite()-
> >
> > that is , I want to write a file (of arbitrary data) that is 100K,
or
> > 1MB (or more) bytes long..
> >
> > Both write() and fwrite() in C allow the user to specify the size of
> > the data to be written.

> Another alternative is to seek to required position and write (at
least) one
> byte...
>
> reqSize = 1048576
> fh = open('junk', 'wb')
> fh.seek(reqSize - 1)
> fh.write('\0')
> fh.close()
>
> Mike.

I interpreted his 'arbitrary data' to mean the same thing & came up with
the same solution (which should be the fastest way to do it in C as
well!).  Anyway, doing some rough timing also seems to show that
creating the string was only taking about 10% of the time that writing
it is, and that the seek solution is about 10x faster that creating the
string & 100x faster that writing the string!  It shows once again that
it pays to find out where the bottleneck is before trying to optimize
the wrong area!

--
Greg





More information about the Python-list mailing list