Rename file if it exists.

Stephen Reese rsreese at
Fri Oct 16 21:33:23 CEST 2009

The script below uploads files to a web server. Currently it
overwrites a file if it already exists. I'm instead trying to rename
the old file with an appended date/timestamp before the new file is
uploaded. I *think* I have the idea down but it's not be implemented
in the script correctly. Any hints would be great, thanks.

#!/usr/bin/env python
import cgi, os
import cgitb; cgitb.enable()
#import os.path
import hashlib
import datetime

try: # Windows needs stdio set for binary mode.
    import msvcrt
    msvcrt.setmode (0, os.O_BINARY) # stdin  = 0
    msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:

form = cgi.FieldStorage()

# Generator to buffer file chunks
def fbuffer(f, chunk_size=10000):
   while True:
      chunk =
      if not chunk: break
      yield chunk

# A nested FieldStorage instance holds the file
fileitem = form['file']

# Test if the file was uploaded
if fileitem.filename:

   # Test to determine if file name already exists in destination and
rename if it does exist to include date.
   if os.path.isfile(file):
      os.rename(file,file + "date")

   # strip leading path from file name to avoid directory traversal attacks
   fn = os.path.basename(fileitem.filename)
   f = open('/var/www/dropbox/' + fn, 'wb', 10000)

   h = hashlib.md5()
   datalength = 0

   # Read the file in chunks
   for chunk in fbuffer(fileitem.file):
      datalength += len(chunk)
   hexdigest = h.hexdigest()

   message = 'The file "' + fn + '" was uploaded successfully with a
MD5 hash value of ' + hexdigest + ', click <a href="#">here</a> to go

   message = 'No file was uploaded'

print """\
Content-Type: text/html\n

More information about the Python-list mailing list