How can I access an uploaded file in universal-newline mode?

前端 未结 1 798
清歌不尽
清歌不尽 2020-12-10 02:58

I am working with a file uploaded using Django\'s forms.FileField. This returns an object of type InMemoryUploadedFile.

I need to access th

1条回答
  •  旧巷少年郎
    2020-12-10 03:31

    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']
    

    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)
    

    0 讨论(0)
提交回复
热议问题