Code # 1: Using the shutil module
The arguments to these functions are all strings that provide file or directory names. The basic semantics tries to emulate the semantics of similar Unix commands as shown in the comments. By default, symbolic links are followed by these commands. For example, if the source file is a symbolic link, then the destination file will be a copy of the file that the link points to.
To copy the symbolic link instead, specify the keyword argument follow_symlinks , as shown in the code below:
Code # 2:
copytree () additionally allows you to ignore copy specific files and directories during the copying process. To do this, provide an ignore function that takes a directory name and a list of filenames as input and returns a list of names to ignore. An example is shown in the code below —
Code # 3:
Since it is common to ignore filename patterns, there is already a
ignore_patterns () utility function provided for this as a show but in the code below.
Code # 4:
How does it work?
- Usage shutil for copying files and directories is mostly straightforward.
- However, one caveat regarding file metadata is that functions like copy2 (), make every effort to preserve this data.
- Basic information such as access times, creation times and permissions will always be preserved, but retaining owners, ACLs, resource forks, and other extended metadata These files may or may not work depending on the underlying operating system and its own user. access permissions.
- The user probably won’t want to use a function like shutil.copytree (), to perform a system backup.
When working with filenames, be sure to use the functions from
os.path for maximum portability (especially when working with both Unix and Windows).
Code # 5: Example
(’/ Users / gfg / programs’,’ abc.py’)
’/ new / dir / spam.py’
’/ Users / gfg / programs / abc .py’
One of the
copytree () when copying directories using
copytree () is error handling. For example, during the copy process, the function may detect broken symlinks, files that cannot be accessed due to permission issues, etc.