We will read the text file in write (w) mode in this Python program. Let’s consider that we have a writecontent.txt file with the content below. We will write content for this file with mode with the help of the below-given steps.
# writecontent.txt
Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.
Steps to solve the program
- Open the file by using open(“file_name”, “w”).
- Where file_name is the file’s name and w is writing mode.
- Using write() method write the data into the file this data will overwrite the previous data.
- Close the file.
# Solution 1:
content = "New Line : This is China"
# open file and provide filename and write mode as (w)
file = open("writecontent.txt", "w")
file.write(content) # write content to file using write method
file.close() # close the file.
# Solution 2: write content into file using function.
def write_content(filepath, content):
file = open(filepath, "w")
file.write(content)
file.close()
write_content("writecontent.txt", content)
Output: Once we add the written content to the file, the existing content will be overwritten, now open the writecontent.txt file, then only the newly added line will be available.
New Line: This is china