Rename file if it exists.

Diez B. Roggisch deets at nospam.web.de
Fri Oct 16 16:24:24 EDT 2009


Stephen Reese schrieb:
> 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:
>     pass
> 
> form = cgi.FieldStorage()
> 
> # Generator to buffer file chunks
> def fbuffer(f, chunk_size=10000):
>    while True:
>       chunk = f.read(chunk_size)
>       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")
>    else:
> 

This isn't working because the else: is dangling. And I think your logic 
is flawed (I might be wrong of course) because you rename the *existing* 
file instead of giving the new one a new data.

Thus e.g. a link to the file (if it's a webserver) will suddenly deliver 
a different file. I doubt that's what you wanted. And you also can only 
upload one file per *day*. Which doesn't sound good to me. You should 
disambiguate further. And if it's ok to append a date, I suggest you do 
that always.

So instead, the logic should be something like this:

import datetime

basename = ... # however you get to that

basename = basename + "_" + datetime.datetime.now().strftime("%Y-%m-%d")

count = 0
filename = basename
while os.path.isfile(filename):
     filename = basename + "." + count
     count += 1


Diez



More information about the Python-list mailing list