Abd-Elaziz Sharaf
Abd-Elaziz Sharaf

Reputation: 334

Flask handle uploaded csv on the fly by csv module

Simply, I need to work with files uploaded without saving it on server

working in cli script using open() every thing is fine,


using flask with file sent from data by ajax request neither open() function nor stream.read() method helped to work with the csv

open throws an exception itself

csv_f = open(request.files['csvfile'].stream, 'rb')
TypeError: expected str, bytes or os.PathLike object, not SpooledTemporaryFile

using .read() I can print it

csv_f = request.files['csvfile'].stream.read()
data = csv.reader(csv_f, delimiter = ',')

print(csv_f)
b'...'

but Iterating also throws exception

for row in data:
_csv.Error: iterator should return strings, not int (did you open the file in text mode?)

I need only a way to work with csv files using csv module on the fly

Upvotes: 0

Views: 447

Answers (1)

Abd-Elaziz Sharaf
Abd-Elaziz Sharaf

Reputation: 334

I found out the problem

the file is going throw request as a binary stream not a normal text

that's why it has a read method but unuseful when itrating

I had to use .decode() like this

request.files['csvfile'].stream.read().decode("utf-8")

instead of this request.files['csvfile'].stream.read()

Upvotes: 1

Related Questions