How do I copy a file in Python?


Question

How do I copy a file in Python?

I couldn't find anything under os.

1
2046
8/15/2018 1:59:09 AM

Accepted Answer

shutil 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. src and dst are path names given as strings.

2521
3/31/2019 5:14:32 AM

┌──────────────────┬───────────────┬──────────────────┬──────────────┬───────────┐
│     Function     │Copies metadata│Copies permissions│Can use buffer│Dest dir OK│
├──────────────────┼───────────────┼──────────────────┼──────────────┼───────────┤
│shutil.copy       │      No       │        Yes       │    No        │    Yes    │
│shutil.copyfile   │      No       │        No        │    No        │    No     │
│shutil.copy2      │      Yes      │        Yes       │    No        │    Yes    │
│shutil.copyfileobj│      No       │        No        │    Yes       │    No     │
└──────────────────┴───────────────┴──────────────────┴──────────────┴───────────┘

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon