How do I copy a file in Python? How do I copy a file in Python? python python

How do I copy a file in Python?


shutil has many methods you can use. One of which is:

from shutil import copyfilecopyfile(src, dst)# 2nd optioncopy(src, dst)  # dst can be a folder; use copy2() to preserve timestamp
  • Copy the contents of the file named src to a file named dst. Both src and dst need to be the entire filename of the files, including path.
  • The destination location must be writable; otherwise, an IOError exception will be raised.
  • If dst already exists, it will be replaced.
  • Special files such as character or block devices and pipes cannot be copied with this function.
  • With copy, src and dst are path names given as strs.

Another shutil method to look at is shutil.copy2(). It's similar but preserves more metadata (e.g. time stamps).

If you use os.path operations, use copy rather than copyfile. copyfile will only accept strings.


FunctionCopies
metadata
Copies
permissions
Uses file objectDestination
may be directory
shutil.copyNoYesNoYes
shutil.copyfileNoNoNoNo
shutil.copy2YesYesNoYes
shutil.copyfileobjNoNoYesNo


copy2(src,dst) is often more useful than copyfile(src,dst) because:

  • it allows dst to be a directory (instead of the complete target filename), in which case the basename of src is used for creating the new file;
  • it preserves the original modification and access info (mtime and atime) in the file metadata (however, this comes with a slight overhead).

Here is a short example:

import shutilshutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # complete target filename givenshutil.copy2('/src/file.ext', '/dst/dir') # target filename is /dst/dir/file.ext


matomo