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.
CSV (comma delimited) will not open correctly and the data within will be displayed incorrectly. This is due to regional Excel settings that have default list separator options where files will either be read with a comma separator or semicolon separator.
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)
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