You are here: Home / Topics / write() and read() in file handling in python

write() and read() in file handling in python

Filed under: Python on 2022-08-04 20:11:57

read()-

read() is a python file function which are used to read the existing file.

Syntax-

f.read()

Here 'f' is the object which points the existing file.

write()-
 write() is a python file function which are used to write in the file.
 If the file is not exist then write() function create new file.

Syntax-
f.write(string)
Here string is the content which we want to insert into the file.

#opne file in write mode
f=open("myfile.txt",'w')
f.write("Data insert into the file")
f.close()

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

output-

Data insert into the file

In this program, initially we open the file named as 'myfile.txt' and 'txt' is shows that file is of type 'text', 
then by f.write("Data insert into the file") we write this string into the file.
then by f.read() we get the all text of the file then we print that.

About Author:
V
Vaibhav Shukla     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.