开发者

Copying a list of paths/files to a directory

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)

How开发者_如何学Cever, 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?


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


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜