Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

python - Getting Type error while opening an uploaded CSV File

I'm developing an application in python with django. User can upload a CSV file. I use file upload to get the file. But, it's not stored any where. I try to take it from request to process the file. While I'm trying to open the file, it gives an error. I use the CSV library exists in python to process. Form elements and attributes used as per django. Request object which I try to take the uploaded file is also django designed object.

import csv
from rootFolder.UploadFileForm

def uploadFile(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            paramFile = open(request.FILES['uploadFile'], 'rb')
            portfolio = csv.DictReader(paramFile)
            users = []
            for row in portfolio:
                users.append(row)

This below line gives the error.

paramFile = open(request.FILES['uploadFile'], 'rb')

The given error is :

TypeError: coercing to Unicode: need string or buffer, InMemoryUploadedFile found

Please kindly give your suggestion if you got any idea on this. Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This works for Python 3

import csv
import io

...

csv_file = request.FILES['uploadFile']
decoded_file = csv_file.read().decode('utf-8')
io_string = io.StringIO(decoded_file)
for line in csv.reader(io_string, delimiter=';', quotechar='|'):
    print(line)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...