Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么我的txt文件不能正确导出换行符?_Python_Django - Fatal编程技术网

Python 为什么我的txt文件不能正确导出换行符?

Python 为什么我的txt文件不能正确导出换行符?,python,django,Python,Django,我知道如何在python中生成和读取txt文件,但当我在django中作为HttpResponse执行时,它无法正常工作 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)

我知道如何在python中生成和读取txt文件,但当我在django中作为
HttpResponse
执行时,它无法正常工作

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

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

尝试更改
text\u string+='{}{}\n'。格式(user.id,user.username)
text\u string+='{}{}\r\n'。格式(user.id,user.username)


查看更多信息

它可以工作!谢谢我想我可能不得不用
open(file,'a')
做一些不可靠的事情,因为这是以前对我来说唯一能正常工作的方法。