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?
Thanks
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With