Best way to write a file n-bytes long

Raymond Hettinger vze4rx4y at verizon.net
Tue Aug 26 18:27:05 EDT 2003


"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.
>
> Python's write only allows a string to be passed in.
>
> Sure, I could create a string that is n Megabytes long, and pass it to
> write, but it seems as though there should be a better way ???
> String manipulation is typically considered slow.

The C coded string methods are not slow.
In Py2.3, 'x' * n  calls str.__mul__ which is implemented
using the C library's memset() function.

It is faster still to use itertools.repeat:

         st = itertools.repeat('X', 1048576)

Of course, your particular use case is I/O bound
(meaning that string construction isn't the
cause of your performance issues).

> st="X" * 1048576
> fh=open("junk","wb")
> fh.write(st)
> fh.close()


Raymond Hettinger






More information about the Python-list mailing list