Best way to write a file n-bytes long

Daniel Klein danielk at aracnet.com
Tue Aug 26 18:41:43 EDT 2003


On 26 Aug 2003 15:04:12 -0700, cappy2112 at yahoo.com (Tony C) wrote:

>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.
>
>st="X" * 1048576
>fh=open("junk","wb")
>fh.write(st)
>fh.close()

Pythons file objects are automatically treated as streams. So you could do
something like this:

st = 'X'
somebignumber = 1048576
fh = open('junk','wb')
for n in xrange(somebignumber):
     fh.write(st)
fh.close()

Daniel Klein





More information about the Python-list mailing list