Save Python Variable to File

Save Python Variable to File

  1. Make Use of String Concatenation to Save a Variable to a File in Python
  2. Make Use of String Formatting to Save a Variable to a File in Python
  3. Make Use of the Pickle Library to Save a Variable to a File in Python
  4. Make Use of the NumPy Library to Save a Variable to a File in Python

Python is perfectly capable of supporting file handling. It allows the programmers to deal with files of different types, perform basic operations like reading and writing, and provide other file handling options to operate on files.

This tutorial discusses the several methods available to save a variable to a file in Python.

We should note that we will use the open() function with its mode set to w in all the methods, which specifies that the given file is opened for writing.

Make Use of String Concatenation to Save a Variable to a File in Python

Concatenation can be simply defined as the integration of two strings into a single object. The concatenation process is carried out using the + operator in Python.

We can use concatenation within the write() function to save a variable to a file in Python. Here, we will also use the str() or the repr() function to convert the variable to a string and then store it in the file.

The following code uses string concatenation to save a variable to a file in Python.

dict1 = {'hello' : 1, 'brother' : 2}
file1 = open("Original.txt", "w") 
str1 = repr(dict1)
file1.write("dict1 = " + str1 + "\n")
file1.close()
 
f = open('Original.txt', 'r')
if f.mode=='r':
    contents= f.read()

The above code provides the following output:

dict1 = {'hello' : 1, 'brother' : 2}

Explanation:

  • The given file is first opened in the write mode by using the open() function.
  • The variable is then converted to a string. We have used the repr() function here, but the str() function can also be used instead.
  • Then, we save the variable into the file using string concatenation within the write() function.
  • The file is then closed. It can then be opened in the read mode to see its contents.

Make Use of String Formatting to Save a Variable to a File in Python

String formatting supplies a huge variety of customizations for the programmer to select from in the code. The % sign is commonly referred to as the interpolation operator, which is utilized to implement string formatting.

Although there are other ways to implement string formatting in Python, the % sign is the oldest and works pretty much on all available versions of Python, making it the most versatile out of the lot.

The % sign, along with a letter representing the conversion type, is marked as a placeholder for the variable.

The following code uses string formatting to save a variable to a file in Python.

dict1 = {'hello' : 1, 'brother' : 2}
file1 = open("Original.txt", "w") 
file1.write("%s = %s\n" %("dict1", dict1))
file1.close()
 
f = open('Original.txt', 'r')
if f.mode=='r':
    contents= f.read()

The above code provides the following output:

dict1 = {'hello' : 1, 'brother' : 2}

Explanation:

  • The given file is first opened in the write mode by using the open() function.
  • Then, we save the variable into the file by using string formatting within the write() function. This eliminates having to convert variables to string in one step manually.
  • The file is then closed. It can then be opened in the read mode to see its contents.

Make Use of the Pickle Library to Save a Variable to a File in Python

The pickle module can be utilized in Python to serialize and de-serialize any structure of an object. However, it can also be implemented to save a variable to a file in Python simply.

The pickle module needs to be imported to the Python code to implement this method without any errors. This method is usually utilized when we need to store multiple variables in a file in Python.

The following code uses the pickle library to save a variable to a file in Python.

import pickle
dict1 = {'hello' : 1, 'brother' : 2}
file1 = open("Original.txt", "wb") 
pickle.dump(dict1, file1)
file1.close

with open('Original.txt', 'rb') as f:
    dict = pickle.load(f)

The above code provides the following output:

dict1 = {'hello' : 1, 'brother' : 2}

Explanation:

  • The pickle module is imported to the Python code first.
  • Then, the given file is opened in the write mode by using the open() function.
  • Then, from the pickle module, the dump() function is applied, which dumps all the entered data in the given file.
  • The file is then closed. It can then be opened in the read mode to see its contents.

Make Use of the NumPy Library to Save a Variable to a File in Python

NumPy, which is an abbreviation for Numerical Python, is a library that makes it possible to work with arrays and supplies several functions for fluent operation on these arrays. However, that is not all, it can also be utilized to save a variable to a file in Python.

Implementing this method is fairly easy and short. We need to generate a list and save this list to the text file of the given name in the code. We will use the numpy.savetxt() function to carry out this process.

The NumPy module needs to be imported to the Python code to use this method without any errors.

The following code uses the NumPy library to save a variable to a file in Python.

import numpy as np
x =  [100,200,300,400,500]
np.savetxt('Original.txt', x)
print(open("Original.txt").read())

The above code provides the following output:

1.000000000000000000e+02
2.000000000000000000e+02
3.000000000000000000e+02
4.000000000000000000e+02
5.000000000000000000e+02

Explanation:

  • The NumPy module is imported to the Python code first.
  • Then, the given file is opened in the write mode by using the open() function.
  • Then, from the NumPy module, the savetxt() function is applied. This saves the text in the file that is passed as its argument.
  • Finally, we use the print statement to get the output of the code.

Related Article - Python File

  • Get All the Files of a Directory
  • Delete a File and Directory in Python
  • Append Text to a File in Python
  • Check if a File Exists in Python
  • Find Files With a Certain Extension Only in Python
  • Read Specific Lines From a File in Python