How to copy file in Python
Using Python to copy file, move file by using os or shutil package in Python. In this tutorial, I will show you how to copy a file from a folder to another folder. There is also an option if you want to move the file instead of copying it.
The shutil package has many methods we can use to copy/move files:
1. Copy file using copyfile from shutil
from shutil import copyfile
copyfile(src, dst)
- Copy the contents of the file named src to a file named dst.
- 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 strings.
2. Copy file/folder using copy from shutil
from shutil import copy
copy(src, dst)
NoteThe difference betweencopy
andcopyfile
is that incopy(src, dst)
the dst can be a directory
3. Copy file/folder using copy2 from shutil
from shutil import copy2
copy2(src, dst)
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 ofsrc
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).
4. Conclusion
The below table shows the functions for copying/moving file/folder
┌──────────────────┬────────┬───────────┬───────┬────────────────┐
│ Function │ Copies │ Copies │Can use│ Destination │
│ │metadata│permissions│buffer │may be directory│
├──────────────────┼────────┼───────────┼───────┼────────────────┤
│shutil.copy │ No │ Yes │ No │ Yes │
│shutil.copyfile │ No │ No │ No │ No │
│shutil.copy2 │ Yes │ Yes │ No │ Yes │
│shutil.copyfileobj│ No │ No │ Yes │ No │
└──────────────────┴────────┴───────────┴───────┴────────────────┘
Last modified October 4, 2020