Python write variable to file

Write variable to file in Python

File handling is an important concept of programming. Python allows us to read and write content to an external file.

In this article, we will discuss several ways to write variable to file in Python.

First, let us discuss the basics of file handling and how to write data to a file since this will be common with all the methods.

  • To write data to an external file, we first open the required file using the open() function. This creates the file object associated with the required file.
  • We need to open it in write mode, so it is necessary to specify the mode as w in the open() function.
  • We can also add the type of the file using t and b while specifying the mode. Here, t indicates a text file, and b indicates a binary file.
  • To write content to this file, we will use the write() function with the file object. We pass the contents as a string.
  • After writing the necessary data, we can close the file using the close() function.
  • We can avoid this close function by using the with statement to open the file. The with statement makes the code more readable, avoids exceptions, and removes the need to close the file.

A variable is a simple object which holds data in the memory and can be of any type. For our examples, we will use a dictionary and write this dictionary to a file. We will convert this dictionary to a string using different methods.

Using the str() function

The str() function is used to typecast a variable into a string. We can use this to convert the dictionary variable to a string and write it to a file.

See the code below.

Output:

The str() function returns the string representation of the dictionary and we write it to the required file.

Using the repr() function

The repr() function works similarly to the str() method for providing string representation of objects. However, it is unambiguous and is used generally for development and debugging processes. It gives the exact representation of the object and does not aim to make it readable, as is the case with the str() function.

For our purpose, although the result is the same, it is generally recommended to use this method over the str() function.

For example,

Output:

Using the string formatting

We can also use string formatting to convert the dictionary variable to a string before writing it to a file. The %s format can be used to make this conversion.

See the following example.

Output:

Using the pickle.dump() function

Pickling is a way to serialize and de-serialize objects. In Python, we can use the pickle module to convert objects to byte stream using the dump() function.

We can use this method to write variable to file in Python. Since it converts objects to byte-stream, we need to open the file in wb mode, which indicates write mode in binary files. We will use this dump() function in place of the write() function. We need to specify the file object and the variable to be written in this file as arguments in the dump() function.

For example,

The above example will write the dictionary d to the sample.txt file as bytes. Therefore if you open the text file you will find a sequence of byte characters. To verify the contents of the file, we can read it using the pickle.load object. We need to open the file in rb mode, which indicates read mode in binary files.

We will read the contents of this file in the following code.

Output:

{‘a’: 0, ‘b’: 1, ‘c’: 2}

Note that it is not advisable to read pickled data from unknown sources. This is because they may contain malware or malicious code.

Using the numpy.savetxt function

You can also use numpy library to write list variable to file in Python. We will create list and save the list to a text file named ‘sample.txt’.

Output:

1.000000000000000000e+01
2.000000000000000000e+01
3.000000000000000000e+01
4.000000000000000000e+01
5.000000000000000000e+01

Now in this article, we discussed different methods on how to write a variable to a file. We worked with file-handling examples and a dictionary, but for other objects, there may be simpler methods available.

For example, for numpy arrays, we can use the numpy.savetxt() to export an array to a text file. So bear in mind that there might be other methods available, but it depends on the variable type.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *