Read a File : File « CGI Web « Python Tutorial

Home
Python Tutorial
1.Introduction
2.Data Type
3.Statement
4.Operator
5.String
6.Tuple
7.List
8.Dictionary
9.Collections
10.Function
11.Class
12.File
13.Buildin Function
14.Buildin Module
15.Database
16.Regular Expressions
17.Thread
18.Tkinker
19.wxPython
20.XML
21.Network
22.CGI Web
23.Windows
Python Tutorial » CGI Web » File 
22.7.1.Read a File
#!/usr/bin/env python
import cgitb
cgitb.enable()

import cgi, os, urllib, md5

print "Content-type: text/html"
print

print """<HTML>
<HEAD>
<TITLE>CGI File Example</TITLE></HEAD><BODY>"""

form = cgi.FieldStorage()
if form.has_key('file'):
    fileitem = form['file']
    if not fileitem.file:
        print "Error: not a file upload.<P>"
    else:
        print "Got file: %s<P>" % cgi.escape(fileitem.filename)
        m = md5.new()
        size = 0
        while 1:
            data = fileitem.file.read(4096)
            if not len(data):
                break
            size += len(data)
            m.update(data)
        print "Received file of %d bytes.  MD5sum is %s<P>" % \
                (size, m.hexdigest())
else:
    print "No file found.<P>"

print """<FORM METHOD="POST" ACTION="%s" enctype="multipart/form-data">
File: <INPUT TYPE="file" NAME="file">
""" % os.environ['SCRIPT_NAME']
print """<INPUT TYPE="submit" NAME="submit" VALUE="Submit">
</FORM>
</BODY></HTML>"""
22.7.File
22.7.1.Read a File
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.