Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 404
Zach Avatar asked Dec 09 '09 18:12

Zach


1 Answers

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)
like image 149
Antoine P. Avatar answered Nov 17 '22 09:11

Antoine P.