Search code examples
pythoncsvweb2py

having trouble opening a csv file in web2py


I'm working on a project in web2py where I need to upload a csv file to a database, then take the information that is in that file and do something with it. I am able to upload a csv file, and in the database I can click on this file, open it, and physically read it, but when I try to open and read it in the controller it doesn't work.

The code in my controller that causes the error looks like this:

csvfile = open(form.vars.csv, 'r')

the error is "FileNotFoundError: [Errno 2] No such file or directory: 'datab.csv.aae72db13bc450af.637376746573742e637376.csv' "

why is this not working?


Solution

  • After the form has been processed, the upload field in the database, and therefore form.vars.csv, simply stores the filename, not the full file path. Rather than manually constructing the full file path and calling open, more simply you can just do:

    filename, csvfile = db.mytable.csv.retrieve(form.vars.csv)
    

    When passed a file name, the .retrieve method of an upload field object returns the original (untransformed) file name as well as the open file object.

    See http://web2py.com/books/default/chapter/29/06/the-database-abstraction-layer#More-on-uploads.