Difference between write and append mode in file handling in python by R4R Team

-In file handling, for inserting a data inside the file, we have a two mode in which we open the file
'w' open file in write mode.
'a' open file in append mode.

- Both mode write the content in the file, if file not exist then they create that file.

Difference-

- for a existing file,
- write mode 'w' erase the previous data of the file and insert new data while append mode don't erase previous data, it append new data with previous one.


program-

#open file in read mode
f=open("myfile.txt",'r')
print(f.read())
f.close()


output-

This is previous data


-In this program, we have a file named as 'myfile.txt' which contain data 'This is previous data'.
-Now we perform both write and appnend mode in this existing file.

Write mode on 'myfile.txt'

program-

#open file in read mode
f=open("myfile.txt",'w')
f.write("This is new data")
f.close()

f=open("myfile.txt",'r')
print(f.read())
f.close()


output-

This is new data


-In this program, we write the new data in existing data and read that file, but only new data will show that means old data was erase by default.

Append mode on 'myfile.txt'

program-

#open file in read mode
f=open("myfile.txt",'a')
f.write("This is new datan")
f.close()

f=open("myfile.txt",'r')
print(f.read())
f.close()


output-

This is previous data
This is new data


-In this program, we append new data in existing file so it don't erase old data and it show old and new data both.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!