12.3 Managing Output Files
Completion requirements
Go through the activity to the end
Use shutil for File and Directory Operations
Python’s built-in shutil module gives you shell-like file management functions.
import shutil
shutil.copyfile('file1.txt','file2.txt')
- This copies the contents in one step from one file to the other. No need to read and write line by line.
The following are some useful shutil functions that copies more than the content of the file. For instance, the metadata like permissions and time-stamps.
| Function | Description |
|---|---|
copyfile(src, dst) |
Copies content of one file to another file. |
copymode(src, dst) |
Copies permissions of a file or directory to another. |
copystat(src, dst) |
Copies permissions and time-stamps of a file or directory to another. |
copy(src, dst) |
Copies file content and permissions. |
copy2(src, dst) |
Like copy(), but also preserves metadata. |
move(src, dst) |
Moves or renames a file or directory. |
copytree(src, dst) |
Recursively copies a directory and its contents. |
rmtree(path) |
Recursively deletes a directory. Be cautious with this one. |
These are all about dealing with the files with Python commands.