首页 > 解决方案 > 为什么我的 txt 文件没有正确导出换行符?

问题描述

我知道如何在 python 中制作和读取 txt 文件,但是当我HttpResponse在 django 中这样做时它无法正常工作。

def abc(request):
    users = User.objects.all()
    filename = "my-file.txt"
    text_string = ''
    for user in users:
        text_string += '{} {}\n'.format(user.id, user.username)
    print(text_string)  # prints properly in the terminal with a new line
    response = HttpResponse(text_string, content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename={}'.format(filename)
    return response

这个文件下载得很好,但是打开时内容是这样的:

1 userA2 userB3 userC

但我希望它看起来像:

1 userA
2 userB
3 userC

我注意到的另一件奇怪的事情是,当我在这个文本编辑器中复制/粘贴内容时,它保留了我期望的新行,但没有按照我想要的方式在文件中显示它。

标签: pythondjango

解决方案


尝试更改text_string += '{} {}\n'.format(user.id, user.username)text_string += '{} {}\r\n'.format(user.id, user.username)

在此处查看更多信息


推荐阅读