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.
Index
There are 2 Methods to copy the content of source file into the destination file
In this method, we use some python modules and use them for copying source file into the destination file.
Steps
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
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
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
I hope, Our code will run successfully and you understand how to copy file in python different ways.
There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…
In this tutorial, I'm going to show you how to install MySQL on your computer.…
Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…
We can redirect any webpage to any other or redirect the whole domain or website…
There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…
Include files in PHP are used in appending various global or config files. We can…