How to Write to a Text File in Python

In this tutorial, we will learn how to write to a text file in Python with clear content of explanation and some examples. You might get clear knowledge about the writing to a file in Python in this post.

You are here to know about the writing to a text file in Python which can be executed by using some functions related to files in Python. In this tutorial we are going to see what are the required syntax and functions for writing to a text file in python.

Writing to a Text File in Python

We all know that a File is a collection of data, to access this files we have some Access Modes in python.

  1. Read Mode
  2. Write mode
  3. Append Mode

In this tutorial we are going to learn Writing to a text file in Python. So, we are going to look after the Write mode.

For writing to a text file in Python we are going to use Write Mode. Lets see what is Write mode, Its is one of the file access modes which is helpful for writing the content to a text file in Python. While writing to a text file in Python there are three main steps to followed .

  • Opening a File
  • Writing to a File
  • Closing a File

While writing to a text file in Python, Firstly the file has to be open in Write Mode , if the exists the file is opened and the pointer points at the beginning of the file and the Data will be Overwritten. If the file doesn’t exists then new file will be created with given file name.

Data Overwritten : It is stated as if the data is present in the file then all the data will be erased and new data will be written.

There are two methods in writing to a text file .

  1. Write() : It will write single line
  2. Write lines() : It will write multiple lines

Lets see an example for Writing to a text file in python .

Writing to a text file in Python

#opening a file
f1 = open('myfile.txt', 'w')
L = ["This is Raju \n ", " This is Roshan \n "]
s = " Hello\n "

#Writing a String to a file
f1.write(s)

#Writing multiple Strings
f1.writelines(L)

#Closing file
f1.close()
#checking if the data is written to file or not

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

Output:

Hello

This is Raju

This is Roshan

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top