Skip to content

Instantly share code, notes, and snippets.

@jigi-33
Last active August 28, 2020 05:58
Show Gist options
  • Save jigi-33/1954c12a79b33130b76545c8db96b04c to your computer and use it in GitHub Desktop.
Save jigi-33/1954c12a79b33130b76545c8db96b04c to your computer and use it in GitHub Desktop.
Copy a file in Python - different usual methods

Some ways to copy a file in Python

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

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 this copy operation, 'src' and 'dst' are pathnames given as strings.

However,

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's a short example:

import shutil

shutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext')  # complete target filename given
shutil.copy2('/src/file.ext', '/dst/dir')  # target filename is /dst/dir/file.ext

Here's a pretty table on this topic:

┌──────────────────┬────────┬───────────┬───────┬────────────────┐
│     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       │
└──────────────────┴────────┴───────────┴───────┴────────────────┘

or

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Function              preserves     supports          accepts     copies other
                      permissions   directory dest.   file obj    metadata  
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
shutil.copy              ✔             ✔                 ☐           ☐
shutil.copy2             ✔             ✔                 ☐           ✔
shutil.copyfile          ☐             ☐                 ☐           ☐
shutil.copyfileobj       ☐             ☐                 ✔           ☐
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Another methods / libs:

  • os module
  • subprocess module
import os
import subprocess

I. Copying files using os module:

os.popen signature:

os.popen(cmd[, mode[, bufsize]])

example
# In Unix/Linux
os.popen('cp source.txt destination.txt')
in Windows
os.popen('copy source.txt destination.txt')

os.system signature:

os.system(command)

# In Linux/Unix
os.system('cp source.txt destination.txt')  
in Windows
os.system('copy source.txt destination.txt')

II. Copying files using subprocess module:

subprocess.call signature:

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

example (WARNING: setting 'shell=True' might be a security-risk)
# In Linux/Unix
status = subprocess.call('cp source.txt destination.txt', shell=True) 
in Windows
status = subprocess.call('copy source.txt destination.txt', shell=True)

subprocess.check_output signature:

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

example (WARNING: setting 'shell=True' might be a security-risk)
# In Linux/Unix
status = subprocess.check_output('cp source.txt destination.txt', shell=True)
in Windows
status = subprocess.check_output('copy source.txt destination.txt', shell=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment