Writing to File in Python

Video Tutorial
FREE
Writing a file thumbnail
This video belongs to
Python Course for Beginners With Certification: Mastering the Essentials
16 modules
Certificate
Topics Covered

Python, renowned for its readability and versatility, provides built-in functions for seamless file manipulation. Whether dealing with plain text or delving into the intricacies of binary data encoded in 0s and 1s, Python provides a robust set of tools to create, write, and read files.

First, understanding the distinction between text and binary files is fundamental.

  • In text files, each line concludes with the End of Line (EOL) character, typically represented as ' \n' in Python.
  • there are no line terminators in binary files, and data is stored in a machine-understandable binary language.

Access Mode

In Python, access modes dictate how a file can be used once opened. They define the operations permitted on the file. Different access modes for reading a file are:

  1. Write only (‘w’): Opens the file for writing, truncating and overwriting existing data if the file already exists. The handle is set at the beginning of the file, and a new file is created if none exists.
  2. Write and Read (‘w+’): Enables reading and writing, with existing data truncated and overwritten. The handle is positioned at the start of the file.
  3. Append (‘a’): Opens the file for writing, creating it if necessary. The handle is positioned at the end, allowing data to be inserted after existing content.

Opening a File in Python

We use the built-in open() function to open any existing or non-existing file. One thing to note here is that whether you’re opening an existing file or want to open a non-existing file ( by creating it) depends on your access mode.

The access modes that help create a new file if it does not exist are – w, w+, a, a+

Let’s see how we can use the open function to open an existing or non-existing file.

The syntax of the function is:

The 'r' is just before the parameters to prevent the characters in the file name from being treated as special characters. For example, if we have "\tapes" in the file address, then "\t" could be treated as the tab character, and an error would be raised. The 'r' represents raw, meaning the string does not contain special characters.

The open function gives us a file object to perform operations. The parameters of the available function are the file name and the access mode in which you wish to open the file. In place of the file name, if the file isn’t in the same directory as the program, we can add the complete file path.

Usage:

Now, if you open a file, you must also close it.

Another important thing to note here is that when dealing with text files, it is recommended that you also specify its encoding as follows:

Closing a File in Python

We use the built-in function close() to close a file. This function closes the file and frees the memory space acquired by that file. You can use the close function if you no longer need the file or if it is required in another access mode.

Usage:

That’s it!

To guarantee that the file closes, even if some exceptions are raised during file handling, a better way is to use the tryfinally block. Any code in the try block is executed first. If any error is raised, it stops executing the try block code and moves to the final block.

Writing to File in Python

We have various access modes to open an existing text file in Python and to write to it, depending on what we need. Even if the text file does not exist, we can use the w or the a access mode to create a text file and then write to it.

Writing to a Text File

There are two functions in Python that help us write into text files:

1. The write() Function in Python

Whatever strings you give as a parameter to this function, it writes it as a single line in the text file. Again, whether the existing contents will be truncated depends on the access mode. If you use the w mode, the contents will be truncated, and your string will be written.

Now, let's take a look at an example. We initially did not have any existing file with the name writing.txt. We're creating it using the w mode. Once we open the new file, it's empty. We're then going to write content into it.

Here, file_obj is the file object. We're opening a file named writing.txt in the w access mode. If this file doesn't exist, it will be created since we have used the w access mode.

We can now write into it like this:

Since we used the open() method to open the file instead of with open(), we also need to close the file.

Let’s see what our file looks like now with the below program.

The non-existent file now has above two lines of content in it. Let's try writing to the file again; it's just another line. Since we closed the file earlier, we need to open it again.

Note how we used the w access mode. The file writing.txt currently exists. The previous time we used the open function to open the file, it did not exist. We created it and then opened it. This time, it just opens in writing mode since it already exists.

Once you run this code, you will see the below file contents:

2. The writelines() Function in Python

Constantly using file.write() for every line we want to write to your file can get tricky. Hence, we can use the writelines() function.

A simple way to use it is to provide a list of strings as a parameter to writelines().

Note that if you open a file with w or a access mode, you can only write to the file and not read from it. In the same way, if you open a file in the r mode, you can only read from it and not write. If you wish to perform both operations simultaneously, use the a+ mode.

Writing to a Binary File

After learning how to read data from a binary file, I'm sure you also know how to write to it. We use the wb mode to write to a binary file.

Example

Human-readable data does not exist in binary form. Consequently, when dealing with an array of numbers such as 1, 2, 3, 4, and 5, it is necessary to transform them into a byte representation before storing them in a binary file. To achieve this, the bytearray() function is employed.

You now know all you need to know about writing into files using Python. To compile your Python code, use this Online Compiler.

Appending to a File

Appending data to a file in Python is an ordinary operation, especially when you want to add new information without overwriting existing content. Achieving this in Python is easily done by utilizing the open() function with the mode parameter set to 'a' (append).

Let's consider the initial contents of the file:

Without precaution, attempting to write to the file directly would result in overwriting these lines. However, using the 'a' mode in the open() function, we can append new data to the end of the file without affecting the existing content.

Here's an example code snippet demonstrating how to append data to a file:

After running the code, the file will look like this:

Writing to a File in Python Using for Statement

In Python, using a for statement can be a powerful and concise way to write data to a file, especially when dealing with iterable objects like lists or strings. This approach enables you to iterate through each element in the iterable and then write it to a file.

Consider the following example, where we have a list of items, and we want to write each item to a file on a new line:

After executing this code, the contents of the file "output.txt" will be:

  • This approach is beneficial when you have a data collection that you want to write to a file sequentially.
  • This method is not limited to lists. It can be adapted for various iterable objects.

Conclusion

After learning about how to write into files in Python, here are some key points that will help you:

  • We use the write() method to insert a single string into a text file and the writelines() method to insert multiple strings into a text file.
  • We must first convert our input into binary form to write to a binary file.
  • To convert an array of numbers into a binary array, we can use bytearray() function.

Read More