×

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

Python Loop through a Dictionary

Introduction in this tutorial, we will discuss in python How to Loop Through a Dictionary. In contrast to other Data Types, which can only retain a single value as an element, a Dictionary...

4 minutes read.

List Comprehension in Python

Sometimes we need new lists that are completely based on previously existing lists, so to perform this operation successfully, some of the programming languages come with a syntactic construct known...

5 minutes read.

Artificial intelligence mini projects ideas in python

Artificial intelligence "The human race started from the invention of the wheel", and today we are about to advance to the Industrial level 4.0, where machines can work, talk, think and...

6 minutes read.

Change Data Type in Python

Python is a dynamic language where it is not always required to consider every variable type. Python supports a wide range of data types, but There are mainly six data...

3 minutes read.

Python Boolean

In this article, you will learn the boolean variables in python, bool() function in python, and bool operators with examples, Boolean Objects in Python. There are the only two possible values...

6 minutes read.

*Args and **Kwargs in Python

Let’s know about ** (dual star / asterisk) and * (star / asterisk) are operators in Python. These stars are used in Python for parameters. Args and kwargs are special...

3 minutes read.

Python eval() function

Python eval() function The eval() function in Python is used to evaluate the given expression. If the specified expression is a legal Python statement, it will be executed. Syntax eval(expression, globals=None, locals=None) Parameter expression: This parameter represents a String,...

1 minute read.

Python Sending Email

Python Sending Email Simple Mail Transfer Protocol (SMTP) is used to handle sending e-mail and routing e-mail between mail servers. When we send an email either form a web-application or from a local software...

3 minutes read.

Python Console

Console in Python is referred as the command line Interpreter- (CLI) and also knows as Shell and it functions as taking input from the human user and interpreting it through...

6 minutes read.

Anaconda python 3 installation for windows 10

If you are a problem solver and like to solve programming questions, the anaconda distribution for python could be one of the best options to use and solve problems in...

3 minutes read.

Check Palindrome in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Python Graph

Python Graph: In Computer Science and Mathematics, a Graph is a pictorial representation of a group of objects or elements where some elements are connected using the links. A graph...

5 minutes read.

How to Call a Function in Python

How To Call a Function in Python Functions are the well-defined and structured piece of code that is used to implement specific functionality. Calling a function in python is the best...

4 minutes read.

Creating Tables using Python MySQL

In this article, we are going to learn how to create tables in databases using Python MySQL. Introduction to Tables: Generally, databases are used in order to store the information in the...

9 minutes read.

Python String rsplit() method

Python String rsplit() method The string.rsplit() method in Python splits a string into a list, starting from the right. If the "max" parameter is not specified, this method will return the...

1 minute read.

Return Statement In Python

Python Return Statement The return statement is generally used for the execution ending and returns the value back to the caller. The return statement can return all types of values and...

2 minutes read.

XXhash Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

6 minutes read.

Python Argmin

Introduction The argmin function is defined as numpy.argmin(). This function returns the index of the minimum value or element from a Numpy array in a specific axis. An array is taken...

3 minutes read.

Python setattr() function

Python setattr() function The setattr() function sets the value of the specified attribute of the specified object. Syntax setattr(object, name, value) Parameter object: This parameter represents any object. name: This parameter represents the name of the attribute you...

1 minute read.

Curdir Python

Python Programming Language Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.