Python Write Text File

In order to perform file operations such as creating, reading, and writing Text File In Python, it has built-in functions. Python is capable of dealing with two types of files in particular: plain text files and binary files, to name a couple.

Throughout this tutorial, we’ll be looking at how to write content into text files using the Python programming language.

How To Write To A File In Python

To write to a text file in Python, you must first complete the steps outlined below.

  1. Opening the file for writing requires the use of the open() method, which must be passed a filepath as a parameter to the function.
  2. Second, we must write to the file, which can be accomplished through the use of several built-in methods such as write(), and writelines().
  3. After completing the write operation, the text file must be closed using the close() function.

Now that we’ve seen how to write to a text file, let’s break down each of these methods before diving into examples.

How Does Python open() Works?

If the file is openable, the open() function returns the corresponding file object.

Syntax:

open(file, mode='w', buffering=-1, encoding='None, errors=None, newline=None, closefd=True, opener=None)

Where,
        file  =  path-like object representing the file path 
        mode  = This is optional Parameter. It is a string that specifies the mode in which the file should be opened.

There are numerous parameters to the open() function. Let’s look at the parameters required for writing to a text file. It opens the file in the mode you specify and returns a file object.

ModeDescription
‘r’Open a file for reading mode (default if the mode is not specified)
‘w’Open a file for writing. Python will create a new file if does not exist or truncates a file content if the file exists
‘x’Create an exclusive file by opening a file.
‘a’Open a file to append the text to. If the file does not exist, it is created.
‘t’Open a file in text mode. (default)
‘b’Open a file in binary mode.
‘+’Open a file for updating (reading and writing)

Methods For Writing Text In A File In Python

In order to write data into a text file, there are two options.

  • write(): writing a line to a text file is accomplished using the write() function. It only inserts a single line into the text file in question.
  • writelines(): writing multiple string lines at once to a text file is accomplished using the writelines() function. The writelines() method accepts an iterable object, such as a list, set, tuple, or another similar type of collection.

Python close() Function Usage

In order to close a file, use the close() function on the file. Performing this operation after data has been written to the file is a requirement and it is a best practice because it frees up the memory space used by that file. There may be an unhandled exception if this happens.

To ensure that the file is properly closed after the write operation is complete, we can make use of the “with” statement. Specifying an explicit close method every time is unnecessary.

Writing Text Files Code Examples

Let us see a series of code examples to read, write, and write lines at once in a file using Python.

Write and Read Text To File Using write()

The following code demonstrates how to use the write() function to write a list of texts to a text file:

#Initializing A List of String To write
listToWrite = ["You Are Visiting", "Coduber.com", "Daily."]

with open("demoFile.txt", 'w') as openFile:
    #Writing Item From The List To The File
    for line in listToWrite:
        openFile.write(line)
        #Adding a New Line
        openFile.write("\n")

Output:

Python Write Text File

If you want to read the file you just created with the above content, use the open function with the ‘r’ mode, which will open the file in read mode and allow you to read it line by line. Let’s look at an example of code below to see how you can do that.

#If you Want To Read A File
with open("demoFile.txt", 'r') as openFile:
    fileContent = openFile.read()
    print(fileContent)
    openFile.close()

Output:

You Are Visiting
Coduber.com
Daily.

Append Lines To Text File And Read The Appended Lines From A Text File

You must first open the text file in the append mode and then perform the write() operation, as shown in the example below if you want to append the line to an existing text file.

#Open the File In the Append Mode
with open("demoFile.txt", 'a') as openFile:
    lineToAppend = "You are Learning Python Here."
    openFile.write(lineToAppend)
    openFile.close()

Output:

How To Write To A File In Python

Now, let’s read the appended line, as well as all of the other lines in the file, to make sure that the code above successfully appended the line to the text file.

#Open the File In the Append Mode
with open("demoFile.txt", 'r') as openFile:
    #In This Example We Will Read the File
    #Line by Line
    for line in openFile.readlines():
        print(line)
    openFile.close()

Output:

You Are Visiting

Coduber.com

Daily.

You are Learning Python Here.

Write Text To File Using writelines() In Python

The writelines() method can be used to write multiple lines into a text file. There is no limit to the number of lines that can be written using the writelines() method. How to write a list in Python? Let’s look at an example.

#Initializing A List of String To write
listToWrite = ["You Are Visiting", "\nCoduber.com", "Daily."]

with open("demoFile.txt", 'w') as openFile:
    #Writing Item From The List To The File
    openFile.writelines(listToWrite)
    openFile.close()

Output:

Write Text To File Using writelines() In Python

As seen in the preceding image, the lines were added to the text file all at once using writelines().

Append Text To File Using writelines() In Python

Open the text file in append mode and perform the writelines() operation as shown below if you want to append multiple lines to the file.

#Initializing the String to Append
textToAppend = "\nThis Line is Append as Example."

#Opening the file in Append Mode
with open("demoFile.txt", 'a') as openFile:
    #Writing Item From The List To The File
    openFile.writelines(textToAppend)
    openFile.close()

Output:

Append Text To File Using writelines() In Python

Writing To UTF-8 Text File

If you use the code from the previous examples to write UTF-8 characters to a text file, you’ll get an error like this:

UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-44: character maps to <undefined>

You must pass the encoding=’utf-8′ parameter to the open() function in order to open a file and write UTF-8 characters to it. The following example demonstrates how to write UTF-8 characters into a text file:

#Initializing the String to Write in UTF-8
utfTextToWrite = "これは別の言語です。"

#Opening the file in Append Mode
with open("demoFile.txt", 'w', encoding='utf-8') as openFile:
    #Writing Item From The List To The File
    openFile.write(utfTextToWrite)

Output:

Writing To UTF-8 Text File

Wrap Up

If you want to append text to a text file, use the open() function in a mode else use the w mode to open the file. Whenever you finish writing in a file, use the close() method to shut it down, or the with statement when you first open it up.

To write to a text file, use the write() and writelines() functions. To write UTF-8 characters into a file, pass the encoding=’utf-8′ argument to the open() function.

If you are still having trouble writing text to a file in Python, please let me know in the comments section and I will be happy to assist you as soon as possible.

Further Read:

  1. [Fixed] Python TypeError: ‘NoneType’ Object Is Not Subscriptable
  2. [Fixed] Python TypeError: ‘list’ object is not callable
  3. Python TypeError: ‘int’ Object Is Not Subscriptable Fix
  4. Python iloc() function – Complete Guide

Leave a Comment