How to copy a Python file?

Asked

Viewed 9,644 times

4

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

1 answer

7


shutil.copyfile

import shutil
shutil.copyfile(fonte, destino)

It is possible to use os.path to obtain paths that work for several operating systems.

For example, to move the file arquivo.txt to the directory dir, 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 the type will occur IOError.

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

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

The destino needs to be a file name and cannot be a directory.

shutil.copy

import shutil
shutil.copy(fonte, destino)

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

shutil.copy2

import shutil
shutil.copy2(fonte, destino)

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.