Write a Python Program to Copy The Contents of a File to Another File

Hi, in this blog let look into how we can Write a Python Program to Copy The Contents of a File to Another File 


copy contents of file to another file



Given a file you have to open the file, read contents of file and write the contents to another file. Lets assume example.txt is the file and sample.txt is the second file. Lets open the file read the contents and write it to another file

fd_read = open("example.txt", "r")
fd_write = open("sample.txt", "w")
data = fd_read.read()
fd_write.write(data)
fd_read.close()
fd_write.close()


Open and Close File Automatically using With 

You can also use with to open the file, read and write contents to another file, lets me show you how.

with open("example.txt", "r") as fd_read, open("sample.txt", "r") as fd_write:
    data = fd_read.read()
    fd_write.write(data)
 

In the above program I am using with to open two files together and close automatically, with in the with statement using the read() and write() function calls.

 

Open File in Binary Read and Write Mode

Assume your first file is not a text file and not sure what type of file it is. Then you can open the file in binary mode by adding "b" to second argument of open() function.

with open("example", "br") as fd_read, open("sample", "bw") as fd_write:
    data = fd_read.read()
    fd_write.write(data)


Conclusion : Try the program by yourself and comment down below for any queries.





Post a Comment

0 Comments