In this Python tutorial, you will learn about Python write variable to file with examples.
Writing a variable to a file in Python can be done using several different methods. The most common method is to use the open function to create a file object, and then use the write method to write the contents of a variable to the file.
Using the repr() function
Using the pickle.dump() function
Using the string formatting
Using the str() function
Method-1: Python write variable to file using the repr() function
The repr() function in Python can also be used to convert a variable to a string before writing it to a file. The repr() function returns a string containing a printable representation of an object.
This can be useful if you want to write a variable to a file and also maintain the original format of the variable.
# Declaring variables for car name, year, and color carname="Swift" caryear="2000" carcolor="white" # Opening a file named "car.txt" in write mode file = open("car.txt", "w") # Using the repr() function to convert the string values to their string representation carname = repr(carname) caryear = repr(caryear) carcolor = repr(carcolor) # Writing the car name, year, and color to the file, with appropriate labels file.write("Car Name = " + carname + "\n" +"Car Year = "+caryear + "\n"+"Car color wp-block-image">
Read: Get current directory Python
Method-2: Python write variable to file using the pickle.dump() function
The pickle module in Python provides dump() function, which can be used to write a variable to a file in a way that allows the variable to be easily restored later.
The dump() function takes two arguments: the variable to be written to the file and the file object to which the variable should be written.
# This code imports the pickle module import pickle # This line creates a dictionary variable named "student" student = # This line opens a file named "student.p" in write binary mode (wb) file = open('student.p', 'wb') # This line writes the "student" dictionary to the "student.p" file using the pickle.dump() function pickle.dump(student, file) # This line closes the "student.p" file file.close()
The above code creates a dictionary variable named “student” and stores some student information in it.
Then, it uses the pickle module to write the “student” dictionary to a file named “student.p” in binary format.
The pickle.dump() function is used to write the dictionary object to the file and the file.close() function is used to close the file after the data is written.
The conversion output is the form of the below image.
To read the data from the file “student”, use the below code.
# This code imports the pickle module import pickle # This line opens a file named "student.p" in read binary mode (rb) file = open('student.p', 'rb') # This line loads the data from the "student.p" file and assigns it to the "student" variable using the pickle.load() function student = pickle.load(file) # This line closes the "student.p" file file.close() # This line prints the contents of the "student" variable print(student)
The above code imports the pickle module and then uses it to read a file named “student.p” which is in binary format, using the pickle.load() function.
The pickle.load() function reads the data from the file and assigns it to the “student” variable.
Then the file.close() function is used to close the file after the data is read. Finally, the print(student) statement is used to print the contents of the “student” variable.
Method-3: Python write variable to file using the string formatting
Python provides several ways to format strings, one of which is using string formatting. This method allows you to insert values of variables into a string, which can then be written to a file.
# This code creates a set variable named "carname" with the value "figo" carname = # This line opens a file named "car.txt" in write mode (w) file = open("car.txt", "w") # This line uses string formatting to write the "carname" variable and its value to the file file.write("%s = %s\n" %("carname",carname)) # This line closes the "car.txt" file file.close()
The above code creates a set variable named “carname” and assigns the value “figo” to it.
Then, it opens a file named “car.txt” in write mode (w) and writes the “carname” variable and its value to the file using string formatting.
The file.write(“%s = %s\n” %(“carname”,carname)) statement is used to write the “carname” variable and its value to the file.
The %s is used as a placeholder for the variable name and the %s\n is used as a placeholder for the variable value.
The \n is used to add a new line after the value so that the next string written to the file will be in a new line. Finally, the file.close() function is used to close the file after the data is written.
Method-4: Python write variable to file using the str() function
The str() function in Python is used to convert any data type to a string. It can be used to convert objects of built-in types such as integers, floating-point numbers, and complex numbers to strings, as well as objects of user-defined types.
# This code creates a dictionary variable named "student" student = # This line opens a file named "student.txt" in write mode (w) file = open("student.txt", "w") # This line converts the "student" dictionary to a string using the str() function and writes it to the file file.write(str(student)) # This line closes the "student.txt" file file.close()
The above code creates a dictionary variable named “student” and then opens a file named “student.txt” in write mode (w).
Then, it converts the “student” dictionary to a string using the str() function and writes it to the file using the file.write(str(student)) statement.
Finally, the file.close() function is used to close the file after the data is written.
You may also like to read the following Python tutorials.
In this tutorial, we learned about how to Python write variable to file and covered the below methods:
Using the repr() function
Using the pickle.dump() function
Using the string formatting
Using the str() function
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.
Make Use of String Concatenation to Save a Variable to a File in Python
Make Use of String Formatting to Save a Variable to a File in Python
Make Use of the Pickle Library to Save a Variable to a File in Python
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.
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.
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.
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.
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.
Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.