Python write variable to file + Examples

By: On:

In this python tutorial, you will learn about Python write variable to file with examples. Also, we will cover the below topics:

  • python write variable to file with open
  • python write variable to file newline
  • python write values to file
  • python write multiple variables to file
  • python save a variable to file pickle

How to write variable to a file in Python?

Now, we will see how to write a variable value to a text file in Python.


In this example, I will show two ways to write values of a variable in Python to a text file.

Also you can check, Python write String to a file

String Concatenation

I am taking three Python variables as carname, caryear, and carcolor, and assigning them a value and next to open a file.

I am using file = open(“filename.txt”, “mode”) and used filename as car.txt. We can use the “w” mode to write the file and there are other modes in the files such as


  • r – read mode.
  • a – append mode.
  • w – writing mode.
  • r+ – both read and write mode.

After opening the file, I used file.write() method to write the contents in the file. Here the contents are carname, caryear, and carcolor. Then use the file.close() method to close the created file.

carname="Swift"
caryear="2000"
carcolor="white"
file = open("car.txt", "w")
file.write("Car Name = " + carname + "\n" +"Car Year = "+caryear + "\n"+"Car color = "+carcolor )
file.close

Below image shows the output. This output is displayed in the new file created named as “car.txt”.

write variable to a file in Python
write variable to a file in Python

Another function repr() it is used to convert a variable in to string.

Example:


carname="Swift"
caryear="2000"
carcolor="white"
file = open("car.txt", "w")
carname = repr(carname)
caryear = repr(caryear)
carcolor = repr(carcolor)
file.write("Car Name = " + carname + "\n" +"Car Year = "+caryear + "\n"+"Car color = "+carcolor )
file.close

In the above example, I have used the repr function to convert a variable into string. After opening the file for each variable repr function is assigned.

Below image shows the output.

How to write variable to a file in Python
write variable to a file in Python

In this particular example, I have taken a car_dictionary var variable of dictionary type that has some default value. Once you execute the code, it will create a .txt file and add the value of the variable to that file.

Example:

car_dictionary = {"Car name" : "baleno"  , "year" : 2009}

file = open("car.txt", "w")
file.write("Car = " + repr(car_dictionary) + "\n")
file.close

We can even create dictionary variables.

Python write variable to file
Python write variable to file

We are getting output as a variable in the new file. In the above example, we have used the path names of the file as the filename as car_dictionary and mode as “w” to open the file for writing. a string containing the variable name as car_dictionary.

string formatting

I have taken a variable such as carname and file = open(“filename.txt”, mode) to open the file and call file. write() method to write content in the file. it contains some data.

Data such as string formats %s, and having a tuple that consists of the variable name and a variable.\n is the newline character which is used when we want to display on a new line.

Example:

carname = {"figo"}

file = open("car.txt", "w")
file.write("%s = %s\n" %("carname",carname))

file.close()

Below image shows the output.

stringformatting output 3

Python write variable to file with open

Let us see how to write variable to file with open. In the below code, I am using file.open(“file.txt”,mode) to open the file.

Example:

carname="Swift"
caryear="2000"
carcolor="white"
file = open("car.txt", "w")
file.write("Car Name = " + carname + "\n" +"Car Year = "+caryear + "\n"+"Car color = "+carcolor )
file.close

Python write variable to file newline

Let us see how to write variable to file with newline in Python.

In Python \n is the newline character which is used when we want to write on a new line.

In the below example, you can see, I have used \n to write Car Name, Car Year, and Car color in new lines.

Example:

carname="Belano"
caryear="2000"
carcolor="silver"
file = open("car.txt", "w")
file.write("Car Name = " + carname + "\n" +"Car Year = "+caryear + "\n"+"Car color = "+carcolor )
file.close

Python write values to file

In this example, I have taken three variables and file = open(“filename.txt, mode) to open the file and used file .write(‘value of the variable’) to get the values assigned to the variable in the textfile created.file.close() to close the file.

Example:

StudentName = "john"
StudentEmail = "[email protected]"
Studentphoneno = "9999995555"
file = open("stud.txt" ,"w")
file.write('john\n')
file.write('[email protected]\n')
file.write('9999995555\n')
file.close()

Below image shows the output in which the values of the variables are displayed in the new file created.

Python write values to file
Python write values to file

Python write multiple variables to file

In the below examples, you can see, I have taken multiple variables such as StudentName, StudentEmail, Studentphoneno.

The below code you can use to write multiple variables to file in Python.

Example:

StudentName = "john"
StudentEmail = "[email protected]"
Studentphoneno = "9999995555"
file = open("Student.txt" ,"w")
file.write("Student Name = "+StudentName + "\n" +"Student Email = "+StudentEmail + "\n"+"Student phone no = "+Studentphoneno )
file.close()

Below image shows the output.This output is displayed in the new file created named as “Student”.

Python write multiple variables to file
Python write multiple variables to file

Python save variable to file pickle

The process of converting the python objects such as list, dictionary, tuples, etc. into byte stream(0,1) is called pickling and the reverse process i.e the process of converting the byte stream into objects is called unpickling.

The pickle is a module. It can be used only after importing the pickle module by the command import pickle.

Example:

student = {"studentname" : "john","student age" : 14,}

import pickle              

file = open('student.p', 'wb')  
pickle.dump(student, file)          
file.close()

In this am using student dictionary and assigning key and value pair i.e key as “studentname” and value is “john”.

And next importing a module pickle and then used file =open(‘student.p’, mode) to open the file and pickle.dump() method to dump the variable in the new file created.

The conversion output is the form of below image.

Python save variable to file pickle
Python save variable to file pickle

To load a file.

Example:

import pickle              

file = open('student.p', 'rb')
student = pickle.load(file)      
file.close()                       

print(student)

In this, I am using student = pickle.load(file) to load the variable of a dictionary.

Below image shows the output :

Python save variable to file pickle
Python save variable to file pickle

You may like the following Python tutorials:

In this tutorial, we learned about how to write variable to file in Python and covered the below topics:

  • How to write variable to a file in Python?
  • Python write variable to file with open
  • Python write variable to file newline
  • Python write values to file
  • Python write multiple variables to file
  • Python save variable to file pickle

Leave a Comment