How to Copy File in Python

Python supports copying of source file into the destination file. Here i’ve described few methods to copy file in python.

It is easier than other programming languages and easy to understand for the developer. We have to import some libraries and write a few lines of code.

There are 2 Methods to copy the content of source file into the destination file

1) Using Python modules

In this method, we use some python modules and use them for copying source file into the destination file.

Steps:

  1. Import python modules shutil and os
  2. Assign destination directory using chdir() function
  3. Use copy() function to copt source file into destination file

Note:

Syntax of shutil.copy function is

shutil.copy('Spath' , 'Dpath')

Here Spath = Path of source file

Dpath = Path of the destination file

Example:

Suppose we have source file sourcefile.txt in D: drive and we want to copy the content of that file into destination file destfile.txt in D: drive. We have to use the above steps for the copying process.

Code:

import shutil,os    # Import two modules shutil and os
os.chdir('D:\')    # Assign directory using chdir() function in which we want to perform copy function
shutil.copy('D:\sourcefile.txt','D:\destfile.txt') #Here first path is for soucefile amd second path is for destinationfile

Also read: How to replace all words in a string using JavaScript

2) Using write function

In this method, we assign the source file path and destination file path to variables. Then we use them for accessing write function in python.

Steps:

Open source file with reading permission and assign it to Spath
Open destination file with write permission and assign it to Dpath
Use write() function to copy content of source file into destination file

Note:

We have to close the destination file after copying the content of source file into the destination file.

We can use close() function for it.

Example:

Suppose we have source file sourcefile.txt in D: drive and we want to copy the content of that file into destination file destfile.txt in D: drive. We have to use the above steps for the copying process.

Code:

Spath = open("D:\sourcefile.txt" , "r") # Open Source file and assign it to Spath with read permission
Dpath = open("D:\destfile.txt" , "w")   # Open destination file and assign it to Dpath with write permission
Dpath.write(Spath.read())               # Use write function to copy Spath into Dpath
Dpath.close()                           # Close Dpath file

I hope, Our code will run successfully and you understand how to copy file in python different ways.

Also read: How to force download file using PHP

Leave a Reply

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

Read previous post:
force download file php
How to Force Download File Using PHP

Generally, we can download files directly by creating hyperlinks. But Images, PDFs and Media files open in a browser rather...

Close