How to read a file and write it to another file in python

Python has inbuilt functions to open, read, write a file and perform various activities around it

Let’s learn about the functions and how to read a file and write it to another file

open()

open function help to open a file and provide the file object as an output. Using this file object, We can able to read or write into the file

f = open("file.txt", "r")
print(f.read())

read()

read function will share the content of the file, based on the size specified as an input to the function. By default, it will get the entire content from the file

f = open("file.txt", "r")
print(f.read())

write()

The write function will write all the content into the specific file, Based on the input (a or w). It will be decided where to write the content (position)

a – end of the file

w – Will remove existing content and write it newly

f = open("file.txt", "a")
f.write("Learn & Share")
f.close()

With the above functions, We can able to read a file and write the content to a new file.

Example:

Creating a file with 3 lines - file1.txt
 
#Writing 2 lines in the file1.txt for reference
f = open("file1.txt", "a")
f.write("1st line n 2nd line n 3rd line")
f.close()
 
Opening a file - file1.txt
 
#open and read the file after the appending:
f = open("file1.txt", "r")
 
# Reading the file content and writing into a variable
filecontent=f.read()
f2 = open("file2.txt", "a")
f2.write(filecontent)
f2.close()
f.close()

To improve the complexity, let’s try reading a file and writing (only a few lines ) it into another file

#Writing 2 lines in the file1.txt for reference

f = open("file1.txt", "a")
f.write("1st line n 2nd line n 3rd line")
f.close()
 
#open and reading entire content of the file
f = open("file1.txt", "r")
linesList=f.readlines()
 
#Using for loop, We are taking the 1st 2 lines and writing into the file
 
f1 = open("file2.txt", "a")
for textline in (linesList[ :2]):
f1.write(textline)
f1.read()
f.close()
f1.close()

Good Luck with your Learning!!

Similar Posts