Rename file if it exists.
rsreese at gmail.com
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.
import cgi, os
import cgitb; cgitb.enable()
try: # Windows needs stdio set for binary mode.
msvcrt.setmode (0, os.O_BINARY) # stdin = 0
msvcrt.setmode (1, os.O_BINARY) # stdout = 1
form = cgi.FieldStorage()
# Generator to buffer file chunks
def fbuffer(f, chunk_size=10000):
chunk = f.read(chunk_size)
if not chunk: break
# A nested FieldStorage instance holds the file
fileitem = form['file']
# Test if the file was uploaded
# Test to determine if file name already exists in destination and
rename if it does exist to include date.
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'
More information about the Python-list