tags:

views:

44

answers:

3

I'm just doing an exercise where I have a list of files (given as absolute paths), which should be copied to a given directory if some sort of flag is set. This is my function to copy the files:

def copy_to(paths, dst):
  if not os.path.exists(dst):
    os.makedirs(dst)

  for path in paths:
    shutil.copy(path, dst)

However, the given solution looks different:

def copy_to(paths, dst):
  if not os.path.exists(dst):
    os.makedirs(dst)

  for path in paths:
    basename = os.path.basename(path)     
    shutil.copy(path, os.path.join(dst, basename))

Is getting the basename of the path and joining it with the path where to copy to really needed here?

+3  A: 

As per the current manual, it is not needed:

shutil.copy(src, dst) Copy the file src to the file or directory dst. If dst is a directory, a file with the same basename as src is created (or overwritten) in the directory specified. Permission bits are copied. src and dst are path names given as strings.

It says that, if dst is a directory, copy() places a file with the same basename of src on dst

Vinko Vrsalovic
+1  A: 

It isn't needed. The documentation says:

Copy the file src to the file or directory dst. If dst is a directory, a file with the same basename as src is created (or overwritten) in the directory specified.

The given solution does this explicitly, rather than letting shutil.copy do it implicitly. That's the only difference.

Tom Anderson
+1  A: 

Hi,

already answered but a few points I noticed. Use of dir here is shadowing the builtin dir. Also, what is os.path.makedirs? On my python (2.6) this gives

>>> os.path.makedirs
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'makedirs'

Do you mean os.makedirs?

Aaron Barclay
+1 Thx, oc I meant os.makedirs :-). Was already wondering if the variable name wasn't shadowing some builtin function, thx again for making this clear.
Helper Method