How do I copy a file in python? I couldn't find anything under os.
shutil has many methods you can use. One of which is:
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.
Look at module shutils. It contains function copyfile(src, dst)
Use the shutils module. http://docs.python.org/lib/module-shutil.html
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.
Take a look at http://docs.python.org/lib/filesys.html for all the file and directory handling functions available in standard Python modules.
import shutil
shutil.copy2('/dir/file.ext', '/new/dir/newname.ext')
or
shutil.copy2('/dir/file.ext', '/new/dir')
copy2
is also often useful, it preserves the original modification and access info (mtime and atime) in the file metadata.
In case you are stuck with Python 2.3 (as I am) you may notice that there is no shutils. But copying a file is a relatively straightforward operation.
def copyfile(source, dest, buffer_size=1024*1024):
"""
Copy a file from source to dest. source and dest
can either be strings or any object with a read or
write method, like StringIO for example.
"""
if not hasattr(source, 'read'):
source = open(source, 'rb')
if not hasattr(dest, 'write'):
dest = open(dest, 'wb')
while 1:
copy_buffer = source.read(buffer_size)
if copy_buffer:
dest.write(copy_buffer)
else:
break
source.close()
dest.close()