Rename file if it exists.
Dave Angel
davea at ieee.org
Sat Oct 17 00:23:32 EDT 2009
Stephen Reese wrote:
>> <snip>
>>
>>
> 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 =s.path.basename(fileitem.filename)
>
> # Include date in filename.
> basename =n
> basename =asename + "_" + datetime.datetime.now().strftime("%Y-%m-%d")
> count =
> fn =asename
> while os.path.isfile(fn):
> fn = basename + "." + count
> count +=
>
> # Open the file for writing
> f =pen('/var/www/apache2-default/' + fn, 'wb', 10000)
>
>
Clearly, the os.path.isfile() is never returning true, because once it
does, you'll get a string error on the next line. You need
fn = basename + "." + str(count)
or something similar.
Anyway, isfile() needs a complete path, there's no way it can guess what directory you plan to use.
To build a complete path, you need something like:
fullname = os.path.join('/var/www/apache2-default/', fn)
You ought to use that on the actual open as well. As long as you're hard-coding the path prefix, plain string concatenation can work, but eventually you'll get the string from somewhere else, and what happens if someone forgets the trailing slash?
More information about the Python-list
mailing list