Write a Python Program to Read Contents of first.txt File And Write Same Content in second.txt File

Hi, in this article lets learn about how to read the first.txt file and write the contents to second.txt file using Python.

Python provides function open() to open a file with read/write/execute option. After opening file with the help of file descriptor you can use read() or write() functions. Lets use this function to open the first.txt for reading the file and then writing the contents to second.txt file.

Once the data is read and written to text files close the files using close() function.


Python Program to Read Contents of first.txt File And Write Same Content in second.txt File

first_fd = open("first.txt", "r")
second_fd = open("second.txt", "w")
data =  first_fd.read()
second_fd.write(data)
first_fd.close()
second_fd.close()
 
 
 

Python Program to Read Contents of first.txt File And Write Same Content in second.txt File using with keyword.

with is a keyword that opens a file and automatically closes it once the local execution is complete.

with open("first.txt", "r") as fdread, open("second.txt", "w") as fdwrite:
    data = fdread.read()
    fdwrite.write(data)

Above example will open two files at one go using with statement. first.txt with read mode and second.txt with write mode. Then read the contents from first and write it to second file descriptor. 

 
 

Python Program to Read Contents of first.txt File And Write Same Content in second.txt File using shutil.

import shutil 
shutil.copy("first.txt", "second.txt")
 
Just import the module shutil and use shutil() function by providing the first.txt as first argument and second.txt as second argument and shutil will copy the contents to another file.

 

copy file contents


 
 
Conclusion : These are the three methods to copy the contents of first.txt to second.txt file. 



Post a Comment

0 Comments