Python COPY File using shutil.copy(), shutil.copystat()

Python COPY File using shutil.copy(), shutil.copystat()

Table of Contents

You must have the simple copying through copy option in windows. As you know Python Copy can do almost anything that you can think of, let’s see how to copy a file using Python. This will help you if you need to write a script of copying data from one place to another in servers where you don’t have access to the user interface.

Let’s take a look at the code.

First we need to import required libraries.

import os
import shutil
from os import path

Now let’s check if the file exists or not

import os
import shutil
from os import path

if path.exists("hello.txt"):
src = path.realpath("hello.txt");
print("Yes file exits")

The output is shown below.

Python COPY File using shutil.copy(), shutil.copystat()

The following function is used to copy the file.

shutil.copy(src,dst)

“src” stands for source location of the file and “dst” stands for destination.

Following command is used to Copy File with MetaData Information 

shutil.copystat(src,dst)

Let’s first use the simple copy.

import os
import shutil
from os import path

if path.exists("hello.txt"):
src = path.realpath("hello.txt");
print("Yes file exits")

dst = src + ".bakup"

shutil.copy(src, dst)
# shutil.copystat(src, dst)

As you can see on the left side that the copy of the file is created.

Python COPY File using shutil.copy(), shutil.copystat()

 Copy File with MetaData Information

MetaData information is file permission, modification time etc. The simple copy only copies the data in the file, not the MetaData information. Let’s now copy the metaData info too.

Here is the code.

import os
import shutil
from os import path

if path.exists("hello.txt"):
src = path.realpath("hello.txt");
print("Yes file exits")
dst = src + ".bakup"
shutil.copy(src, dst)
shutil.copystat(src, dst)
Python COPY File using shutil.copy(), shutil.copystat()

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training
Enroll Free demo class