0

I know how to make and read from txt files in python, but it's not working properly when I do it as an HttpResponse in 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

This file downloads just fine, but the content looks like this when opened:

1 userA2 userB3 userC

But I am expecting it to look like:

1 userA
2 userB
3 userC

Another odd thing I noticed is when I copy / paste the contents in this text editor, it retains the new lines I'm expecting, but is not displaying it as I want in the file.

1 Answers1

1

Try changing text_string += '{} {}\n'.format(user.id, user.username) to text_string += '{} {}\r\n'.format(user.id, user.username)

See more info here

adam_th
  • 397
  • 3
  • 11
  • It works! Thanks! Figured I might have had to do something wonky with `open(file, 'a')`, because that's the only way it worked **properly"* for me before. – CyberHavenProgramming Aug 05 '19 at 16:34