I was looking at my top search queries on google the other day and I noticed this blog was referenced at number 4 for copying folders in python. I do not have a post that covers this though. I have decided to do a daily series on how to replace shell scripts with Python starting with this post about copying files and folders.
Copying files is simple in Python. Actually, all shell script-like operations are.
import shutil # This is the module that will replace most shell operations shutil.copy('/path/to/somefile', 'path/to/the/copy') # works just like cp shutil.copy2('somefile', '/path/to/copy') # works just like cp -p
Not too hard. You say you want to copy a directory recursively? It could not be easier.
import shutil shutil.copytree('src/directory', 'dst/directory') # This copies the tree and the targets of symlinks shutil.copytree('src/directory', 'dst/directory', symlinks=True) # This copies the tree and the symlinks themselves
If you want to do something more complex than shutil.copytree, then you will want to use os.walk, which I will cover in the next few days.
Posted by
on January 8, 2009
at 7:58
Tagged as:
python
shell_scripting
