python - 为什么我的 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
我注意到的另一件奇怪的事情是,当我在这个文本编辑器中复制/粘贴内容时,它保留了我期望的新行,但没有按照我想要的方式在文件中显示它。
解决方案
尝试更改text_string += '{} {}\n'.format(user.id, user.username)
为text_string += '{} {}\r\n'.format(user.id, user.username)
在此处查看更多信息
推荐阅读
- split - 将大文件拆分为每个 10,000 行的文件的命令是什么?
- javascript - 如果Xpath返回元素列表(selenium-python),如何找到第一个元素
- r - 将 sf 文件与不同的几何类型组合,然后在 r 中找出哪些文件彼此在一定距离内
- flutter - 通过监听 pageController 重建部分页面
- javascript - 修改我以前有效的本机应用程序内容后,海拔突然无法正常工作
- java - 带有 spark 库的 AWS Lambda 给出 OutOfMemoryError
- angularjs - 如何放置正确的值来选择由 angularjs 生成的选项值?
- c - 测试一个目录是否设置了 MS_NOEXEC 标志?
- sql - 在不更改游标位置的情况下检查 SQL SYS_REFCURSOR
- f# - 如何在 F# 中派生记录类型?