How to write text file in python

Introduction:How to write text file in python

In this tutorial you will learn how to write text file in python.

There are three basic simple step for writing text file in python are illustrated below

  1. open()
  2. write()
  3. close()

There are two major modes used for writing purpose

  • w
  • a

There are two ways for writing text to file in python. Based on our purpose we can used any of them.

  1. write()
  2. writelines()

Syntax for writing text file are shown below.

f=open('file_path', 'w'):
f.write("Single-line string")

Explanation: How to write text file in python

For writing text file in python first we have to follow three simple steps shown below.

open()

This method is used to a open file. It take two parameters one is file path and another one is mode. For writing purpose we will only use two modes which is explain below.

  • w– This will create a file if the specified file does not exist and give writing access to file.
  • a– will create a file if the specified file does not exist and give appending access to file.

Syntax: For Open() method

f = open("file_path", "w")

write()

Once the file is open and having access for writing then you can use two inbuilt methods for writing text file in python.

write()

The write() method is used to insert the string str1 in single line of text file.

Syntax: For writing text file in python using write().

f = write("Single-line string")

writelines()

The writelines() method is used for List of string elements. With the help of writelines() you can use tuple and set also for inserting text in file using python. Each string is inserted in a text file. writelines() method is used for inserting multiple strings at single time.

Syntax: For writing text file in python using writelines().

l=['car','Bicycle','Bike']
f = writelines(l) 

close()

The close method is used to close the file and deallocate the resources.

f.close()

Examples: For writing text file in python.

Example1

f = open("demo.txt", "w")
f.write("Writing Some Content by using w mode")
f.close()

#open and read the file after the appending:
f = open("demo.txt", "r")
print(f.read())

Example2

f = open("demo2.txt", "a")
f.write("Appending more content using a mode")
f.close()

#open and read the file after the appending:
f = open("demo2.txt", "r")
print(f.read())

Example3

l=['car','Bicycle','Bike']
f = open("demo3.txt", "a")
f = writelines(l) 
f.close()

#open and read the file after the appending:
f = open("demo3.txt", "r")
print(f.read())

Was this article helpful?
YesNo

Leave a Comment