如何以通用换行模式访问上传的文件? [英] How can I access an uploaded file in universal-newline mode?
问题描述
我正在使用Django的 forms.FileField
上传的文件。这将返回一个类型为 InMemoryUploadedFile
的对象。
I am working with a file uploaded using Django's forms.FileField
. This returns an object of type InMemoryUploadedFile
.
我需要以通用换行模式访问此文件。任何关于如何做这个而不保存然后重新打开文件的想法?
I need to access this file in universal-newline mode. Any ideas on how to do this without saving and then reopening the file?
谢谢
推荐答案
如果您使用的是Python 2.6或更高版本,可以在将文件读入内存后使用 io.StringIO
类(使用read()方法)。示例:
If you are using Python 2.6 or higher, you can use the io.StringIO
class after having read your file into memory (using the read() method). Example:
>>> import io
>>> s = u"a\r\nb\nc\rd"
>>> sio = io.StringIO(s, newline=None)
>>> sio.readlines()
[u'a\n', u'b\n', u'c\n', u'd']
要在django视图中实际使用此选项,可能需要将输入文件数据转换为unicode:
To actually use this in your django view, you may need to convert the input file data to unicode:
stream = io.StringIO(unicode(request.FILES['foo'].read()), newline=None)
这篇关于如何以通用换行模式访问上传的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!