How to copy a file in Python?

2

How to copy a fonte file to a destino file in Python?

    
asked by anonymous 30.08.2016 / 19:47

1 answer

5

shutil.copyfile

import shutil
shutil.copyfile(fonte, destino)

You can use os.path to get paths that work for multiple operating systems.

For example, to move the file arquivo.txt to the dir directory, just do:

import shutil
import os
shutil.copyfile(fonte, os.path.join(destino,'dir'))

If the directory does not exist or is not accessible, an exception of type IOError will occur.

If the destination file already exists, it will be overwritten.

shutil.copyfile only copies the contents of files and ignores metadata.

destino must be a filename and can not be a directory.

shutil.copy

import shutil
shutil.copy(fonte, destino)

shutil.copy is similar to shutil.copyfile , but accepts a directory as a destination. In this case, if the destination does not have a file name, the same file name of fonte will be used in the destino folder.

shutil.copy2

import shutil
shutil.copy2(fonte, destino)

The shutil.copy has the same behavior as shutil.copy2 , but also copies the metadata.

    
30.08.2016 / 19:47