Rename file if it exists.

Stephen Reese rsreese at gmail.com
Sat Oct 17 15:31:19 CEST 2009


> 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?
>

Thanks Dave, got it working with the following bit:

   # strip leading path from file name to avoid directory traversal attacks
   fn = os.path.basename(fileitem.filename)
   path = '/var/www/apache2-default/'
   filepath = path + fn

   # Include date in filename.
   filepath = filepath + "_" + datetime.datetime.now().strftime("%Y-%m-%d")

   count = 0
   tmp_fn = filepath + "." + str(count)
   while os.path.isfile(tmp_fn):
      count += 1
      tmp_fn = filepath + "." + str(count)
   filepath = tmp_fn

   # Get the new filename for the users viewing pleasure
   displaypath, tmp_split = os.path.split(filepath)

   # Open the file for writing
   f = open(filepath , 'wb', 10000)



More information about the Python-list mailing list