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.

File Copy in Python

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

Method 1: Using Python modules

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

Steps

  • Import python modules shutil and os
  • Assign destination directory using chdir() function
  • 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

Read Also: How to Generate Authorization(oauth2)/Bearer Token for Firebase V1 API in Python

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

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

Method 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

Read Also: How to force download file using PHP

Conclusion

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

Leave a Reply

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