PY0018 Python COPY File using shutil.copy(), shutil.copystat()
Posted by Superadmin on November 10 2018 13:56:20

Python Copy File Methods

Python provides in-built functions for easily copying files using the Operating System Shell utilities.

Following command is used to Copy File

shutil.copy(src,dst)

Following command is used to Copy File with MetaData Information

shutil.copystat(src,dst)

Here are the steps to copy file in Python

Step 1) Before, we copy a file, we need to get the the path to the original file in the current directory. In the code -

  1. Declaring variable
  2. Applying split function on variable

Python OS Module, Shell Script Commands

Code Explanation

Step 2) We use Shutil Module to create a copy of the existing file. Here we used to create a copy of our existing file "guru99.txt."

Python OS Module, Shell Script Commands

Code Explanation

Step 3) Copy function only copies the content of the file but no other information. To copy meta-data associated with the file, file permission and other information you have to use "copystat" function. Before we run this code, we have to delete our copy file "guru99.text.bak".

Python OS Module, Shell Script Commands

Once you deleted the file and run the program it will create a copy of your .txt file but this time with all the information like file permission, modification time and meta-data information. You can go to your O.S shell to verify the information.

Python OS Module, Shell Script Commands

Here is the code

import os
import shutil
from os import path

def main():
    # make a duplicate of an existing file
	if path.exists("guru99.txt"):
    # get the path to the file in the current directory
        src = path.realpath("guru99.txt");
    
	#seperate the path from the filter
	head, tail = path.split(src)
	print("path:" +head)
	print("file:" +tail)
	
	#let's make a backup copy by appending "bak" to the name
	dst = src+".bak"
	# nowuse the shell to make a copy of the file
	shutil.copy(src, dst)
	
	#copy over the permissions,modification
	shutil.copystat(src,dst)
	
if __name__=="__main__":
	main()

Step 4) You can fetch the information about the text file last modified

Python OS Module, Shell Script Commands

Here is the code

#
# Example file for working with o.s path module


import os
from os import path
import datetime
from datetime import date, time, timedelta
import time

def main():


    # Get the modification time
    t = time.ctime(path.getmtime("guru99.txt.bak"))
    print(t)
    print(datetime.datetime.fromtimestamp(path.getmtime("guru99.txt.bak")))


if __name__ == "__main__":
    main()

Summary