×

Write Text files in Python

Let's discuss writing the text file in detail. Generally, writing text also follows the same procedure as like reading text. It varies only in some specific places.

Steps followed for writing a text file:

  1. Opening the text file
  2. Writing the text
  3. Closing the text file

Opening the text file:

  • The open() method is used to open the text file.
  • Syntax of open()
    open(filepath,mode)
  • As we all know, the characters inside the parenthesis of the method/function are known as Parameters. “filepath” and “mode” are Parameters defined within the method.
  • Here "filepath" indicates the file's path (i.e., the location of the file) and it should be mentioned in order to access the file and open it.
  • Whereas mode depends on the kind of operation, we perform. To perform a write operation, we have to use ‘w’ to overwrite the existing text. We can also use ‘a’ to append something to the end of an existing text file. If you want to create a new file, you have to mention the new file name as filepath and 'x' as mode.
  • So, depending on the operations, the mode varies. As we’ve already discussed, ‘a’ is used to append. Here, append is used to insert some new text into an already existing text file at the end.

Example for Opening a text file (in write mode):

f = open(“C:\Users\Documents\Custom Office Templates”,’w’)

We have opened the file in 'w' mode, i.e., write mode, as we want to write some text in the file. This is how we use modes to open a file. We are writing the text in the "Custom Office Templates" file. The one mentioned above is the path of the “Custom Office Templates” file.

Example for Creating a new file:

f = open(“newFile.txt”,’x’)

We have opened the file in ‘x’ mode as we want to create a new text file. ".txt" is the extension of text files, and "newFile” is the name of the new file.

Writing the text:

  • ‘a’ and ‘w’ modes are used to write text in a file.
  • We use write() and writelines() method to write text.
  • If there are multiple lines of input, write() takes the input one after the other line whereas writelines() takes the complete input of lines simultaneously.
  • Syntax of write()
    var.write()
  • Syntax of writelines()
    var.writelines()

Closing the text file:

  • After writing the text, the final operation is to close the file using the close() method.
  • It is mandatory to close the file as soon as the work is completed in order to prevent unnecessary access.
  • It is safe if you close the files immediately after usage.
  • Syntax of close() :
    var.close()
  • You can close the file without using the close() method also. The text file will be automatically closed using the "with" statement.
  • Syntax of “with”:
with open(filepath,mode) as var1:
var2 = var1.write() 
  • The variable need not call the "close method" as there is an automatic close reflex, i.e., "with", to close the file.

Example programs determining opening, writing, appending, and closing operations:

Example 1:

The file already consists of the following text:

You’ve entered Custom Office Templates.
I’ve been waiting for you.
My hearty welcome to you.

Program:

f = open(“C:\Users\Documents\Custom Office Templates”,’a’)
f.write(“Hope you’re doing good”)
f.close()
# read the file after appending
f = open(“C:\Users\Documents\Custom Office Templates”,’r’)
print(f.read())

Output:

You’ve entered Custom Office Templates.
I’ve been waiting for you.
My hearty welcome to you.
Hope you’re doing good.

Explanation:

Variable “f” is assigned with the opening of the file in append mode. “f” calls the method write() to write the given text. As it is in append mode, the text is added to the text that is already present in the file. When the variable calls the read method after writing the text, all the 4 statements are printed.

Example 2:

The file already consists of the following text:

Hello !! You’re in my computer.

You have my permission to enter.

Program:

f = open(“C:\Users\MyComputer”,’w’)
f.write(“Hope you’re doing good.”)
f.close()
# read the file after appending
f = open(“C:\Users\Documents\Custom Office Templates”,’r’)
print(f.read())

Output:

Hope you’re doing good.

Explanation:

Variable “f” is assigned with the opening of the file in write mode. “f” calls the method write() to write the given text. As it is in write mode, the text will overwrite the text which is already present in the file. When the variable calls the read method after writing the text, only the statement mentioned in the write method is printed.

In this way, the output varies when the mode of operation changes. Even though the programs are similar, the output of the program varies. This is how you write text in the files.


Related Topics

Collections in python

In this tutorial, we will see what is collection in python.  Further, we will see in-depth the different kinds of collections in python. Collections Collections in python are the built-in module used...

9 minutes read.

Python Logistic Regression with Sklearn & Scikit

In this article, we'll walk through a tutorial for utilising the Python Sklearn (formerly known as Scikit Learn) package to implement logistic regression. To assist you in remembering the concept,...

18 minutes read.

Iterate a Dictionary in Python

In this tutorial, we will learn how to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to store data values,...

3 minutes read.

Python String isalnum() method

Python String isalnum() method The string.isalnum () method in Python returns a boolean value true if all characters in the string are alphanumeric else for any other value it returns false. Syntax String.isalnum() Parameter NA Return This...

1 minute read.

How to Install Scikit-Learn

Sklearn or Scikit-learn is a python library used for machine learning. It contains many features like classification, regression, clustering, and Dimensionality reduction algorithms. Sklearn is used to build machine learning...

3 minutes read.

GUI to extract lyrics from a song Using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

4 minutes read.

Python Dictionary fromkeys() method

Python Dictionary fromkeys() method The dictionary.fromkeys() method in Python creates a new dictionary from the given sequence of elements and returns a dictionary with the specified keys and values. Syntax dictionary.fromkeys(sequence[, value]) Parameter sequence- This...

1 minute read.

Android apps for coding in python

Nowadays, it is the generation of smartphones. The world can be seen and acknowledged with a single click on your mobile phone. Everyone uses mobile phones to do any work,...

9 minutes read.

Python String title() method

Python String title() method The string.title() method in Python returns a string where the first character in every word is upper case. If the word contains a number or a symbol,...

1 minute read.

Python Program for Tower of Hanoi

In this tutorial, we will examine and learn about the Python coding used to create the video game Tower of Hanoi. Before seeing the game's step-by-step implementation in Python, we...

3 minutes read.

Python Super function

The super function is used to access and call the methods or functions involved in the parent class during Inheritance. What is Inheritance? The process where the parent class inherits some of...

3 minutes read.

Python Uses

Python has advanced in recent years to rank among the programming languages that are most often used globally. It is utilized in everything, including machine learning, software testing, and website...

4 minutes read.

Python Program to check whether a given number is Armstrong or not

Program to check whether a given number is Armstrong or not A number is said to be an Armstrong if the sum of each digit's cube of a given number equals...

1 minute read.

Import Function in Python

In Python programming language, the import keyword plays an important role in the whole code because it makes one module make available in another module. Import is used to structure...

3 minutes read.

Python Data Structures

Python Data Structures: Python is a programming language used worldwide for various fields such as building dynamic websites, artificial intelligence and many more. However, there is data that plays a...

18 minutes read.

Python hash() function

Python hash() function The hash() function in Python returns the hash value of the object (if it has one).  Syntax hash(object) Parameter obj : This parameter represents the object which we need to convert into hash. Return This...

1 minute read.

Find whether the given stringnumber is palindrome or not

Problem statement Sam is found of playing with strings. One day he thought of finding whether a string is a palindrome or not. He wanted to develop a computer process to...

2 minutes read.

How to Convert int to str in Python

How to Convert int to str in Python In the last article, we studied how we convert a variable with string datatype to integer datatype and discussed different data types available...

4 minutes read.

Working with CSV files in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

7 minutes read.

Python Redis Example

Introduction: Redis, representing Distant Word reference Server, is a kind of key-esteem NoSQL server. Redis is intended to help circle capacity for determination, holding information after power is stopped, and stores information...

5 minutes read.