How to write a variable to a file in Python?

Today, We want to share with you python write variable to file.In this post we will show you python append to file, hear for python write variable to/file new line we will give you demo and example for implement.In this post, we will learn about how to take two inputs in one line in python? with an example.

How To Read and Write Files in Python 3?

Writing a simple variable to a file data results in a file all the containing the variable name as well as the value.

USE STRING CONCATENATION TO WRITE A VARIABLE TO FILE

first of all you can Use open(file, mode) with the pathname of a file as file as well as mode as “w” to open the file for writing. Use repr(object) with object as the main file variable to convert the variable to a string.

Now, Calling file.write(data) with data as a data string concatenation of 3 main ways: a string containing the variable name and =, the string version of the variable, as well as “\n”.

Use file.close() methods to close file.

Example 1:
“\n” creates newline for next write to file

live_pdata_list = {"a" : 1, "b" : 2}

file = open("example.txt", "w")
str_dictionary = repr(live_pdata_list)
file.write("live_pdata_list = " + str_dictionary + "\n")

file.close()

EXAMPLE.TXT


live_pdata_list = {'a': 1, 'b': 2}

USE STRING FORMATTING TO WRITE A VARIABLE TO FILE

first of all you can Use open(file, mode) with the real pathname of a file as file as well as mode as “w” to open the file for writing.

And then Calling easy to use file.write(data) with data as the string formats “%s %d” followed by % as well as a tuple data containing a string of the main variable name, as well as the variable.

Use file.close() methods to close file.

live_pdata_list = {"a" : 1, "b" : 2}

file = open("example.txt", "w")
file.write("%s = %s\n" %("live_pdata_list", live_pdata_list))

file.close()

EXAMPLE.TXT

live_pdata_list = {'a': 1, 'b': 2}

I hope you get an idea about python write to text file.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment