如何上传和读取文件?

时间:2014-08-25 15:32:26

标签: python

我正在尝试使用HTML标记上传文件并通过python读取它。以下是我正在尝试做的代码片段。

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")

我收到以下错误:

  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'

我错过了什么?

1 个答案:

答案 0 :(得分:2)

HTML中的<form>元素没有正确的enctype=属性。

以下是上传CSV文件的示例。请注意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>'''

参考: