[Tutor] Remove last newline only in print / open / read function

Dave Angel davea at davea.name
Fri Apr 25 12:14:31 CEST 2014

Chris <ch2009 at arcor.de> Wrote in message:
> Hi,
> I'm a Python Newbie. Probably, this is a simple question.

But what is your context? Your Python version (apparently 2.x,
 since you're using print as a statement, rather than a function)?
 What os, and what is stdout pointing to,  since you're pretending
 that you can write binary data to it?

> I've a function that offers a ZIP-file for download:
> def download_cert(form, config):
>    cn     = form['cn'].value
>    serial = pki.util.serial_from_cn(config, cn)
>    files  = pki.util.cert_files(config, cn, serial, True)
>    try:
>       name = path.join(tempfile.mkdtemp(), cn + '.zip')
>       zip  = zipfile.ZipFile(name, 'w')
>       for file in files:
>          zip.write(file, path.basename(file))
>       zip.close() (1)
>    except:
>       pki.cgi.start_html('Internal error', True)
>       pki.cgi.show_error(str(sys.exc_info()[1]))
>       pki.cgi.show_link('Go Back')
>       pki.cgi.end_html()
>    else:
>       print 'Content-Type: application/zip'
>       print 'Content-Disposition: attachment;filename=' + cn + '.zip'
>       print
>       print open(name).read() (2)

print adds a newline.  Use write () instead. 
         sys.stdout.write (open (name).read ())

This assumes stdout is opened in binary mode,  so that bytes that
 happen to look like a newline are not corrupted.

>       os.remove(name)
>       os.rmdir(path.dirname(name))
> The ZIP file on the server is okay (1), but when it's sent to the client
> (2), there's a linefeed in the last line. This makes the zip invalid. So
> how can I remove the last linefeed only?

Minimum change is to add a comma at the end of the print
 statement.  But I'd prefer write method,  to be parallel with the
 read ().

Do you know that memory is not a problem,  since you're reading
 the entire temp file in before writing any of it to stdout?  If
 you're not sure,  replace this with a loop.


More information about the Tutor mailing list