簡體   English   中英

Python:正在提供文件,所有回車符都丟失在文本文件中

[英]Python: Serving files, All carriage returns lost in text file

我正在使用鏈接https://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

最初以提交的形式獲取數據,提交后,我處理數據以生成“ config”並將其寫到文件中。 然后在有效時將文件作為下載傳遞回用戶。 效果很好,但我遇到的問題是我的情況是文件是文本,因此下載文件時,它的文本形式為無CR / LF的文本。

關於如何解決這個問題有什么建議嗎?

以二進制模式打開。

open(the_file, 'rb')

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

默認設置為使用文本模式,該模式可以在書寫時將'\\ n'字符轉換為特定於平台的表示形式,並在讀取時將其轉換為特定於平台的表示形式。 因此,打開二進制文件時,應在模式值后附加“ b”以二進制模式打開文件,這將提高可移植性。 (即使在對二進制文件和文本文件沒有不同對待的系統上,追加“ b”也很有用。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM