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.
Table of Contents
- 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 theopen()
function. - We can also add the type of the file using
t
andb
while specifying the mode. Here,t
indicates a text file, andb
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. Thewith
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.
1 2 3 4 5 |
d = {'a':0,'b':1,'c':2} with open('sample.txt', 'w') as f: f.write('dict = ' + str(d) + '\n') |
Output:
1 2 3 |
dict = {'a': 0, 'b': 1, 'c': 2} |
The str()
function returns the string representation of the dictionary and we write it to the required file.
Further reading:
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,
1 2 3 4 5 |
d = {'a':0,'b':1,'c':2} with open('sample.txt', 'w') as f: f.write('dict = ' + repr(d) + '\n') |
Output:
1 2 3 |
dict = {'a': 0, 'b': 1, 'c': 2} |
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.
1 2 3 4 5 |
d = {'a':0,'b':1,'c':2} with open('sample.txt', 'w') as f: f.write("%s = %s\n" %("dict", d)) |
Output:
1 2 3 |
dict = {'a': 0, 'b': 1, 'c': 2} |
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,
1 2 3 4 5 6 |
import pickle d = {'a':0,'b':1,'c':2} with open('sample.txt', 'wb') as f: pickle.dump(d,f) |
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.
1 2 3 4 5 6 |
import pickle d = {'a':0,'b':1,'c':2} with open('sample.txt', 'rb') as f: print(pickle.load(f)) |
Output:
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’.
1 2 3 4 5 6 7 8 |
import numpy as np d = [10,20,30,40,50] np.savetxt('sample.txt',d) print(open("sample.txt").read()) |
Output:
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.