473,748 Members | 2,793 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Best way to write a file n-bytes long

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()

thanks
Jul 18 '05 #1
6 16616
Tony C enlightened us with:
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.


Why not create a string that is 1 KB long and write that n*1024 times?

Sybren
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Jul 18 '05 #2

"Tony C" <ca*******@yaho o.com> wrote in message
news:8d******** *************** ***@posting.goo gle.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.repea t:

st = itertools.repea t('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
Jul 18 '05 #3
On 26 Aug 2003 15:04:12 -0700, ca*******@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(somebign umber):
fh.write(st)
fh.close()

Daniel Klein

Jul 18 '05 #4

"Tony C" <ca*******@yaho o.com> wrote in message
news:8d******** *************** ***@posting.goo gle.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.

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

thanks


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.

Jul 18 '05 #5
"Michael Porter" <mp*****@despam med.com> wrote in message
news:3f******** *************@n ews.dial.pipex. com...

"Tony C" <ca*******@yaho o.com> wrote in message
news:8d******** *************** ***@posting.goo gle.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

Jul 18 '05 #6

"Dialtone" <di************ ************@ar uba.it> schrieb im Newsbeitrag
news:87******** ****@vercingeto rix.caesar.org. ..
ca*******@yahoo .com (Tony C) writes:

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


For little files (less than 2 or 3 Mb I think) your code is the
fastest I can think of. But growing There is a new version which is a
lot faster


All this is valid in a very limited scope only.
- Consider limited RAM (lets say 128 MB) - you will be extremely slowed down
by thrashing.
- Consider on-the-fly compression (Windows NTFS): The 1000 MB testdate will
be reduced to 1 Byte!

Kindly
Michael P

Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2111
by: Herve MAILLARD | last post by:
Hi, I have to write a software doing the following : - Load a file (containing data) Data will be display in a Treeview and are typed as following Equipement Bloc Tag It could have for each Equipement, many blocs and for each bloc, many tags.
7
11058
by: Jimbo | last post by:
What's the best format to save a configuration file? I'm currently using an INI extension and I write it like a normal ascii file. Is this the best way? I've heard of using XML to create a config file. What would be the best format? Thank you.
5
5052
by: Andrew S. Giles | last post by:
I thought I would post here, as I am sure someone, somewhere has run into this problem, and might have a good solution for me. I am writing an applicaiton in C# that will accept data and then put it into an Excel spreadsheet. Easy, right? Well it is, until you have to get the data from another application that is written in Borland C++ PowerBuilder 5. The situation is that the Borland Code isnt going to get re-written (too expensive,...
12
3166
by: Nettan | last post by:
Hi What is the best way to write to a textfile, is it with FileSystemObject or with StreamWriter? Thanks /Nettan
3
2140
by: gordon | last post by:
Hi I am looking to store some details about a user's configuration choices, in particular the place where they have installed some data files, the OS that they use, and their Windows user name. This information is used in a windows C#.net application. I would like to capture this info the first time that the user opens the app, but each subsequent time to make sure that the location is current when they open the application. This is...
3
1983
by: Nemisis | last post by:
Guys, I would like to write a error handler, or something, that will allow me to write to a database when an error occurs on my site. I am trying to implement this in the global.asax file a the moment, but am having problems when a 404 error occurs, i cant access sessionstate. Is writing this code in the global.asax file the best way to do this? I have been searching on the net and hear alot about httphandlers? Will a httphanlder...
7
2235
by: Gladen Blackshield | last post by:
Hello All! Still very new to PHP and I was wondering about the easiest and simplest way to go about doing something for a project I am working on. I would simply like advice on what I'm asking so I can go and learn it myself through doing (best way for me). I am building a card game as a learning-project as it involves many (to most of the) things that I would like to learn to do with PHP.
9
1571
by: Brian Cryer | last post by:
I've developed software (vb.net) that renders maps using svg. My manager would like this "mapping component" to be migrated into a library so it can easily be used by other web based applications. So far so good. However, the page that generates the svg (currently a .aspx file) writes directly to response. Unless I'm being silly, it doesn't look like I can put a .aspx file into a web control library, so what would be the best way to...
2
7651
by: hotflash | last post by:
Hi All, I found the best pure ASP code to upload a file to either server and/or MS Access Database. It works fine for me however, there is one thing that I don't like and have tried to fix but don't have any luck is to do a form validation. This script requires the files: db-file-to-disk.asp and _upload.asp. There is a DESCRIPTION field in the db-file-to-disk.asp file, what I want to do is the user has to field out this fied before...
10
3924
by: Brendan Miller | last post by:
What would heavy python unit testers say is the best framework? I've seen a few mentions that maybe the built in unittest framework isn't that great. I've heard a couple of good things about py.test and nose. Are there other options? Is there any kind of concensus about the best, or at least how they stack up to each other? Brendan
0
8830
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9541
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9321
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9247
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8242
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6074
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4602
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2782
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.