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.


import_contacts

You may also like:

Related Posts

  • Python copy file to another directory
    17 January

    How to copy file to another directory in Python

    Table of ContentsWays to copy file to another directoy in PythonUsing file handlingUsing the shutil libraryUsing the pathlib libraryUsing the os moduleUsing the subprocess moduleConclusion In this article, we will see different ways to copy file to another directory in Python. We can read and write files in Python. We can also work with paths […]

  • Check if variable is String in Python
    13 January

    Check if variable is String in python

    Table of ContentsHow to check if a given variable is of the string type in Python?Using the isinstance() function.Using the type() function.Check if function parameter is String In this post, we will see what is a string in Python and how to check whether a given variable is a string or not. There are many […]

  • Count the number of characters in a String in Python
    13 January

    Count number of characters in a string in python

    Table of ContentsWays to count the number of characters in a string in PythonUsing the len() functionUsing the for loopUsing the collections.Counter classConclusion In this post, we will see how to count number of characters in a String in Python. We can think of strings as a collection of characters, with every character at a […]

  • Pandas apply function to column
    12 January

    Pandas apply function to column

    Table of ContentsHow do I apply function to column in pandas?Using dataframe.apply() functionUsing lambda function along with the apply() functionUsing dataframe.transform() functionUsing map() functionUsing NumPy.square() function We make use of the Pandas dataframe to store data in an organized and tabular manner. Sometimes there, is a need to apply a function over a specific column […]

  • Copy file Python
    12 January

    How to Copy File in Python?

    Table of ContentsCopy file using the shutil module in PythonCopy file using the copyfileobj() function in PythonCopy file using the copyfile() function in PythonCopy file using the copy() function in PythonCopy file using the copy2() function in PythonCopy file using the operating system command in PythonCopy file using the os module in PythonCopy file using […]

  • What is percent in python
    11 January

    What is % in Python?

    Table of ContentsWhat is % Operator in Python?The % Operator with strings in pythonThe % Operator as a placeholder for variables  in pythonThe % Operator as format specifiers in pythonConclusion In this article, we will cover what is % in Python and what are different ways to use % in Python. In python, there are […]

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.