Cómo copiar un archivo usando python? [duplicar]


Esta pregunta ya tiene una respuesta aquí:

Lo primero que tengo que mencionar aquí, soy nuevo en python.

Ahora tengo un archivo ubicado en:

a/long/long/path/to/file.py

Quiero copiar a mi directorio personal con una nueva carpeta creada:

/home/myhome/new_folder

Mi resultado esperado es:

/home/myhome/new_folder/a/long/long/path/to/file.py

¿hay alguna biblioteca existente para hacer eso? Si no, ¿cómo puedo lograrlo?

Author: pb2q, 2012-10-11

2 answers

Para crear todos los directorios de destino de nivel intermedio que podría usar os.makedirs() antes de copiar:

import os
import shutil

srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'


assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)
 59
Author: jfs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-25 13:11:23

Echa un vistazo a shutil. shutil.copyfile(src, dst) copiará un archivo a otro archivo.

Tenga en cuenta que shutil.copyfile no creará directorios que no existan. para eso, use os.makedirs

 22
Author: ewok,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-11 16:16:39