One of the many features that are popular is the file editing powers of the python programming language. In this article, we are going to discuss how to use this functionality of python write to a file in a proper manner.

We will also be discussing some examples based on-

  • Python write text to a file
  • How to write to a file in python

There are various access modes for opening an existing text file in Python and writing something inside it.

To open a file, we need to use the built-in open function

The Python file open function returns a file object that contains methods and attributes to perform different operations for opening files in Python.

The syntax for opening a file in Python:

fileObject  = open("filename", "mode")

where filename = name of the file that is opened

mode = which mode the file is being opened in

There are two access modes that help us to create a text file and then write to it. They are the write(w) and the append(a) modes.

Using the write() function to write text to a file

The two access modes that we discussed above perform a bit differently when used on a text file. The write mode is used when the user wants to overwrite the text file and insert a new string inside the file. The old data inside the text file will be deleted.

Example: Python write text to a file

file = open("filewrite.txt", "w")
file.write("This text will be written in the file.")
print(file.read())
file.close()

Output:
This text will be written in the file.
On the other hand, the append mode is used when the user wants to keep the contents of the text file intact while adding new text to it. There will be no overwriting or deletion of the previous data inside the text file.

Example:

file = open("filewrite.txt", "a")
file.write("This text will be added to the text file as a new line.")
print(file.read())
file.close()

Output:
This text will be added to the text file as a new line.

Writing to a binary file in Python:-

We can use the wb access mode while writing to a binary file in Python.

Example:

file = open("binary_file.bin", "wb")
nums = [1, 2, 3, 4, 5]
arr = bytearray(nums)
file.write(arr)
file.close()

As the binary data is not human recognizable, Therefore when we have to write an array of numbers like 1, 2, 3, 4, 5 we need to first convert them into a byte representation to store it in the binary file. For that purpose, we use the built-in bytearray() function. This helps us to store it and use it to write to a binary file in Python.

So, in this article, we get to know how to write a file in Python using various techniques. We also came across different access modes used to write in the text as well as binary files using the Python programming language.

More article related to Python :

Program: gameOfWar.py

What does != mean in Python?