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 -
Code Explanation
path.split function on source variableStep 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."
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".
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.
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
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