views:

142

answers:

2

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

A: 

InMemoryUploadedFile object have same api as file object, and it have newlines attr (universal-newline mode avaible):

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            f = request.FILES['file']
            print f.readlines()
    else:
        form = UploadFileForm()
    return render_to_response('upload.html', {'form': form})
slav0nic
It isn't instantiated with a newlines attribute. I played around with it, but couldn't figure out a way to manually add it. That's more the information I'm looking for.
Zach
A: 

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']
Antoine P.