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 = "+carcolor )
# Closing the file
file.close
The above code is used to write the car name, year, and color to a text file named “car.txt”.
- The variables carname, caryear, and carcolor are defined with the appropriate values. The file is opened in write mode using the open() function. The repr() function is used to convert the string values to their string representation.
- This is done to ensure that any special characters in the string are properly escaped when written to the file.
- The car name, year, and color are written to the file with appropriate labels, using the write() function. Finally, the file is closed using the close() function.
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 = {"studentname" : "john","student age" : 14,}
# 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.
Read: Python Count Words in File
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 = {"figo"}
# 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.
Read: Python shutil copy file + Examples
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 = {"studentname" : "john","student age" : 14}
# 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.