Vimal
Vimal

Reputation: 339

How to upload and read a file?

I am trying to upload a file using HTML tags and read it through python. Here is the code snippet on what I am trying to do.

def upload_file(self):
    cgitb.enable()
    log.debug("file has yet to be uploaded")
    form = cgi.FieldStorage()
    fileitem = form['CSV'].value
    log.debug(fileitem)
    if fileitem:
        fn = os.path.basename(fileitem)
        with open(fn, 'r') as csvfile:
            reader = csv.reader(csvfile)
            for row in reader:
                log.debug(row)
        log.debug("file uploaded")
    else:
        log.debug("No file was uploaded")

I get the following error:

  File "/base/data/home/apps/s~voicecurvetestcalls/trial.378220245396013618/handler/kellyhandler.py", line 43, in upload_file
    with open(fn, 'r') as csvfile:
IOError: [Errno 2] No such file or directory: 'Calllog.csv'

What am I missing?

Upvotes: 0

Views: 4566

Answers (1)

Robᵩ
Robᵩ

Reputation: 168696

The <form> element in your HTML does not have the proper enctype= attribute.

Here is an example of uploading a CSV file. Note the enctype="multipart/form-data":

#!/usr/bin/python2.7

import csv
import cgi
import cgitb
cgitb.enable()

print "Content-Type: text/html"
print ""
print "<html><body><p>Hello!</p>"

form = cgi.FieldStorage()

if 'CSV' in form and form['CSV'].file:
    print '<p>%s : </p>'%form['CSV'].filename
    print "<table>"
    reader = csv.reader(form['CSV'].file)
    for row in reader:
        print "<tr>"
        for item in row:
            print "<td>%s</td>"%item
        print "</tr>"
    print "</table>"

print '''
<form method="POST"  enctype="multipart/form-data">
    <input type="file" name="CSV" />
    <input type="submit"/>
</form></body></html>'''

Reference:

Upvotes: 2

Related Questions