gpt4 book ai didi

Python:服务文件,所有回车符在文本文件中丢失

转载 作者:行者123 更新时间:2023-12-01 05:42:14 27 4
gpt4 key购买 nike

我正在使用链接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

最初以表单形式获取数据,提交后,我处理数据以生成“配置”并将其写入文件。然后,当有效时,将文件作为下载传递回给用户。它工作得很好,除了我遇到的问题是,在我的情况下,文件是文本,所以当下载文件时,它作为一个没有 CR/LF 的文本 block 出现。

关于如何解决这个问题有什么建议吗?

最佳答案

以二进制模式打开。

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

关于Python:服务文件,所有回车符在文本文件中丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17247220/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com