How not to copy a file to standard output in PythonSuppose that you are quickly bashing together a CGI that as part of its job has to spit out a file. When I needed to do this recently, I reflexively wrote more or less:
(Because this was reading from a file, my usual objections to using file iteration don't apply.) Somewhat later I got a politely phrased report from the person that this
was for to the effect that the PDFs this CGI was supposed to hand out to
people were corrupt. He even helpfully reported that testing with The problem is, of course, that all of the forms of reading lines
at a time from a file keep the terminating newline on the line,
and then (For some people, the easiest solution would be to use ' In theory the more efficient way is to use read plus write to read in
large sized but not memory-busting chunks. I was going to say that this
requires handling short writes and buffering, but that's not correct;
unlike the underlying stdio (In theory this code has a second bug; I should be opening the file in binary mode just in case. In practice, I ignore binary mode; I am not writing Python code that will ever run on Windows machines.) |
These are my WanderingThoughts GettingAround This is part of CSpace, and is written by ChrisSiebenmann. * * * Atom feeds are available; see the bottom of most pages. Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web |