Account
Categories

write() Method


Definition:

The write() method writes text into a file.

If you pass a string as a parameter, it writes the text into the file.

It must be a string; otherwise, it raises an error.

Before using it, open the file in "w" mode.

It deletes the previous data and writes the new data into the file.

Syntax:

file_object.write(string)

Example:

file = open("file1.txt", "w")

file.write("Hello Python")

file.close()

Suppose file1.txt contains:

Rahul Kumar
Priya Sharma
Sohan Khanna
Lata Singh

Output (file content after write):

Exercise

Write a Python program using write() method to write text into a file.