Python comes with the open()
function to handle files. We can open the files in following modes:
read
: Opens the file in reading mode.write
: If the file is not present, it will create a file with the provided name and open the file in reading mode. It will overwrite the previous data.append
: This is the same as opening in write mode but it doesn’t overwrite the previous data.line by line
Open the file1
, which has content in reading mode.
Open the file2
in writing mode.
Use for in
loop to go through every line in file1
and write to file2
.
Content is written to file2
.
Close both the files.
We will check if the content is written into file2
or not by opening the file2
in reading mode and printing the content.
Close the file2
.
In the following code snippet, you can also check that file2.txt
is created. Compare the list of before-after files in the output.
import os# print files in present dir before creating file2print("List of files before")print(os.listdir())print("\n")#open file1 in reading modefile1 = open('file1.txt', 'r')#open file2 in writing modefile2 = open('file2.txt','w')#read from file1 and write to file2for line in file1:file2.write(line)#close file1 and file2file1.close()file2.close()#open file2 in reading modefile2 = open('file2.txt','r')#print the file2 contentprint(file2.read())#close the file2file2.close()#print the files after creating file2, check the outputprint("\n")print("List of files after")print(os.listdir())print("\n")
read()
methodIt is the same as above except that we use read()
method to read the content file1
.
Check line 15
, where we are reading the content from file1
with file1.read()
and writing it to file2
.
import os# print files in present dir before creating file2print("List of files before")print(os.listdir())print("\n")#open file1 in reading modefile1 = open('file1.txt', 'r')#open file2 in writing modefile2 = open('file2.txt','w')#read from file1 and write to file2 using read methodfile2.write(file1.read())#close file1 and file2file1.close()file2.close()#open file2 in reading modefile2 = open('file2.txt','r')#print the file2 contentprint(file2.read())#close the file2file2.close()#print the files after creating file2, check the outputprint("\n")print("List of files after")print(os.listdir())print("\n")
We can open files with the with
keyword, so we don’t need to close files.
import os# print files in present dir before creating file2print("List of files before")print(os.listdir())print("\n")#reading from file1 and writing to file2with open("file1.txt", "r") as file1:with open("file2.txt", "w") as file2:file2.write(file1.read())#reading from file1with open("file2.txt") as file2:print(file2.read())#print the files after creating file2, check the outputprint("\n")print("List of files after")print(os.listdir())print("\n")