python script - How do I copy a file in Python?
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.
dst are path names given as strings.
How do I copy a file in Python?
I couldn't find anything under
- it allows
dstto be a directory (instead of the complete target filename), in which case the basename of
srcis 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 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
You can use one of the copy functions from the
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Function preserves supports accepts copies other permissions directory dest. file obj metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― shutil.copy ✔ ✔ ☐ ☐ shutil.copy2 ✔ ✔ ☐ ✔ shutil.copyfile ☐ ☐ ☐ ☐ shutil.copyfileobj ☐ ☐ ✔ ☐ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
import shutil shutil.copy('/etc/hostname', '/var/tmp/testhostname')
Directory and File copy example - From Tim Golden's Python Stuff:
import os import shutil import tempfile filename1 = tempfile.mktemp (".txt") open (filename1, "w").close () filename2 = filename1 + ".copy" print filename1, "=>", filename2 shutil.copy (filename1, filename2) if os.path.isfile (filename2): print "Success" dirname1 = tempfile.mktemp (".dir") os.mkdir (dirname1) dirname2 = dirname1 + ".copy" print dirname1, "=>", dirname2 shutil.copytree (dirname1, dirname2) if os.path.isdir (dirname2): print "Success"
Look at module shutil. It contains function copyfile(src, dst)
For large files, what I did was read the file line by line and read each line into an array. Then, once the array reached a certain size, append it to a new file.
for line in open("file.txt", "r"): list.append(line) if len(list) == 1000000: output.writelines(list) del list[:]
I suggest using Swati's answer, but supposing you have a text file and don't want to use additional libraries in your code just to copy it, you can use the following one-liner:
with open(source, 'r') as src, open(dest, 'w') as dst: dst.write(src.read())