Rename file if it exists.
Stephen Reese
rsreese at gmail.com
Fri Oct 16 21:12:14 EDT 2009
> 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
The script is working and appending the date to newly uploaded files
but it is not adding the count? Any recommendations? Is the problem
due to os.path.isfile(fn): being just the file name and not the full
path? Thanks.
# strip leading path from file name to avoid directory traversal attacks
fn = os.path.basename(fileitem.filename)
# Include date in filename.
basename = fn
basename = basename + "_" + datetime.datetime.now().strftime("%Y-%m-%d")
count = 0
fn = basename
while os.path.isfile(fn):
fn = basename + "." + count
count += 1
# Open the file for writing
f = open('/var/www/apache2-default/' + fn, 'wb', 10000)
More information about the Python-list
mailing list