Home > Mobile >  How to parse csv into dictionary in Python without saving file?
How to parse csv into dictionary in Python without saving file?

Time:07-12

CSV file uploaded by user and then I want to parse it to dictionary without actually saving the uploaded file.

I found this reference and tried it https://riptutorial.com/flask/example/32038/parse-csv-file-upload-as-list-of-dictionaries-in-flask-without-saving but it gave me an error

@app.route('/upload', methods=['POST'])
def fileUpload():

    if request.method == 'POST':
        f = request.files['file']
        fstring = f.read()
        csv_dicts = [{k: v for k, v in row.items()} for row in
                     csv.DictReader(fstring.splitlines(), skipinitialspace=True)]
    return "success"

         <form action = "/upload" method = "POST" enctype="multipart/form-data">
                <input type = "file" name = "file">
                <input type = submit>
            </form>

_csv.Error: iterator should return strings, not bytes (the file should be opened in text mode)

how can I manage this error?

CodePudding user response:

Your error says your file is encoded, decode it.

fstring = f.read().decode("utf8")

CodePudding user response:

Just pass the file object itself to the csv dict reader. It will work with most file-like objects that feature at least .read method.

@app.route('/upload', methods=['POST'])
def fileUpload():

    if request.method == 'POST':
        csv_dicts = [{k: v for k, v in row.items()} for row in
                     csv.DictReader(request.files['file'], skipinitialspace=True)]
    return "success"
  • Related