Python: Serving files, All carriage returns lost in text file
Question: I'm using the method described in the link
<http://stackoverflow.com/a/8601118/2497977>

    
    
    import os
    import mimetypes
    from django.core.servers.basehttp import FileWrapper
    
    
    def download_file(request):
       the_file = '/some/file/name.png'
       filename = os.path.basename(the_file)
       response = HttpResponse(FileWrapper(open(the_file)),
                           content_type=mimetypes.guess_type(the_file)[0])
       response['Content-Length'] = os.path.getsize(the_file)    
       response['Content-Disposition'] = "attachment; filename=%s" % filename
       return response
    

Initially get data in a form, when submitted, i process the data to generate a
"config" and write it out to a file. then when valid, pass the file back to
the user as a download. It works great except I'm running into the problem
that in my situation the file is text, so when the file is downloaded, its
coming as a blob of text without CR/LF.

Any suggestions on how to address this?


Answer: Open with binary mode.

    
    
    open(the_file, 'rb')
    

<http://docs.python.org/2/library/functions.html#open>

> The default is to use text mode, which may convert '\n' characters to a
> platform-specific representation on writing and back on reading. Thus, when
> opening a binary file, you should append 'b' to the mode value to open the
> file in binary mode, which will improve portability. (Appending 'b' is
> useful even on systems that don’t treat binary and text files differently,
> where it serves as documentation.)

