shutil.copy2()
shutil.copy2() method in Python is used to copy the content of the source file to the destination file or directory. This method is identical to shutil.copy() method but it also tries to preserve the file’s metadata.
Example:
Directory Used
Python3
# Python program to explain shutil.copy2() method # importing os module import os # importing shutil module import shutil # path path = '/home/nikhil/Desktop/new' # List files and directories # in '/home/User/Documents' print ( "Before copying file:" ) print (os.listdir(path)) # Source path source = "/home/nikhil/Desktop/new/pdf.py" # Print the metadeta # of source file metadata = os.stat(source) print ( "Metadata:" , metadata, "\n" ) # Destination path destination = "/home/nikhil/Desktop/new/copy_pdf.py" # Copy the content of # source to destination dest = shutil.copy2(source, destination) # List files and directories # in "/home / User / Documents" print ( "After copying file:" ) print (os.listdir(path)) # Print the metadata # of the destination file matadata = os.stat(destination) print ( "Metadata:" , metadata) # Print path of newly # created file print ( "Destination path:" , dest) |
Output:
Before copying file:
[‘pdf.py’, ‘pdf1.pdf’]
Metadata: os.stat_result(st_mode=33204, st_ino=58068385, st_dev=2050, st_nlink=1, st_uid=1000, st_gid=1000, st_size=887, st_atime=1619538642, st_mtime=1618307699, st_ctime=1618307700)
After copying file:
[‘copy_pdf.py’, ‘pdf.py’, ‘pdf1.pdf’]
Metadata: os.stat_result(st_mode=33204, st_ino=58068385, st_dev=2050, st_nlink=1, st_uid=1000, st_gid=1000, st_size=887, st_atime=1619538642, st_mtime=1618307699, st_ctime=1618307700)
Destination path: /home/nikhil/Desktop/new/copy_pdf.py
Directory
10 Python File System Methods You Should Know
While programming in any language, interaction between the programs and the operating system (Windows, Linux, macOS) can become important at some point in any developer’s life. This interaction may include moving files from one location to another, creating a new file, deleting a file, etc.