Python CGI 读取客户端CSV文件的简单实现
CSV文件是指Comma Separated Value (CSV)文件,Excel可以导出此类文件。
下面的例子简单实现了从客户端上传至服务端存放,再用python的csv模块读取文件,返回给浏览器显示,并删除服务端存放的文件的过程。
转载的时候请注明本站,您的支持是我最大的动力。
CGI-BIN文件:myputfile.py
#!c:\python25\python
#!python
import cgi, string, os, sys
import csv,codecs
import time
sys.stderr = sys.stdout # show error msgs
form = cgi.FieldStorage( ) # parse form data
print "Content-type: text/html\n" # with blank line
clientfile = form['clientfile'].value
filename = './uploads/%s.csv' % str(int(time.time()))
print """
Putfile response page
Content-Type" content="text/html; charset=gb2312" />
Putfile response page"""
print '''[writing content into %s]''' % filename
f = open(filename,'w')
f.write(str(clientfile))
f.close()
f = file(filename)
csvreader = csv.reader(file(filename)) #阅读CSV文件,写入的话,用csv.writer(file(filename))
csvreader = csv.reader(f)
for row in csvreader:
print '|'.join(row)
f.close()
os.remove(filename)
print '''[file %s has been removed]''' % filename
print """"""
HTML文件:putfile.html
html>title>upload csv file/title>
body>
form enctype="multipart/form-data" method="post" action="/cgi-bin/myputfile.py">
h1>Select client file to be uploaded/h1>
p>input type=file size=50 name=clientfile>
p>input type=submit value=Upload>
/form>
/body>/html>