Write variable to file in python

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.

Related Posts

  • Python add commas to number
    11 September

    Python add commas to number

    Table of ContentsUsing the format() function to add commas to numbers in PythonUsing the fstrings to add commas to numbers in PythonUsing the regular expressions to add commas to numbers in PythonUsing the locale module to add commas to numbers in Python Python allows us to format values to get the final result in our […]

  • Write array to CSV in Python
    30 August

    Python write array to CSV

    Table of ContentsUsing the pandas.to_csv() function to write array to CSV fileUsing the numpy.tofile() function to write array to CSV fileUsing the numpy.savetxt() function to write array to CSV fileUsing the file-handling methods to write array to CSV fileUsing the writerows() function to write array to CSV file A CSV file is a simple text […]

  • Multiply in Python
    30 August

    Multiply in Python

    Table of ContentsMultiply operator in PythonMultiplying a string with an integerMultiplying all the elements of a listUse the for loop to multiply all the elements of a listUse the functools.reduce() function to multiply all the elements of a listUse the numpy.prod() function to multiply all the elements of a listUse the math.prod() function to multiply […]

  • Auto clicker in Python
    30 August

    How to make auto clicker in Python

    Table of ContentsUsing the pynput module to create an auto clickerUsing the pyautogui module to create an auto clickerUsing the pywin32 (winauto32api) module to create an auto clicker Python has inbuilt modules and methods which allow it to detect and perform keyboard and mouse inputs. We can create an auto-mouse clicker in Python. An auto-clicker […]

  • Iterate through files in directory in Python
    30 August

    Iterate through files in directory in python

    Table of ContentsUsing the os.scandir() function to iterate through files in a given directory in Python.Using the os.listdir() function to iterate through files in a given directory in Python.Using the os.walk() function to iterate through files in a given directory in Python.Using the pathlib module to iterate through files in a given directory in Python.Using […]

  • Inverse matrix in Python
    24 August

    Inverse matrix in python

    Table of ContentsUsing the Gauss-Jordan method to find the inverse of a given matrix in Python.Using the numpy.linalg.inv() function to find the inverse of a given matrix in Python. The inverse of a matrix in simple mathematics can be defined as a matrix, which when multiplied by the original matrix, gives out the Identity matrix. […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.