Write Multiple Variables to a File using Python
Storing multiple variables in a file is a common task in programming, especially when dealing with data persistence or configuration settings. In this article, we will explore three different approaches to efficiently writing multiple variables in a file using Python. Below are the possible approaches to writing multiple variables to a file in Python.
- Using the repr() function
- Using the string formatting
- Using the str() function
Using the repr() function
In this approach we are using the repr() function to convert each variable into its string representation, preserving its data type andwrite them to a file named 'output.txt' in the format of variable assignments, allowing for easy reconstruction of the variables when read back from the file.
n = "GeeksforGeeks"
f = 2009
p = True
with open('output.txt', 'w') as file:
file.write("website_name = " + repr(n) + '\n')
file.write("founded_year = " + repr(f) + '\n')
file.write("is_popular = " + repr(p) + '\n')
Output
website_name = 'GeeksforGeeks'
founded_year = 2009
is_popular = True
Explanation: This code writes the values of three variables n, f, p (which are website name, founded year and bool for is popular) to a file (output.txt) with their names and repr() representations.
Using the string formatting
In this approach, we are using string formatting to write multiple variables (n, f and p) to a file named 'output.txt', creating a clear and human-readable representation of the data with formatted labels and values.
n = "GeeksforGeeks"
f = 2009
p = True
with open('output.txt', 'w') as file:
file.write("Website Name: {}\n".format(n))
file.write("Founded Year: {}\n".format(f))
file.write("Is Popular: {}\n".format(p))
Output
website_name = 'GeeksforGeeks'
founded_year = 2009
is_popular = True
Using the str() function
In this approach, we are using the str() function to convert each variable (n, f and p) into strings and writes them to a file named 'output.txt', presenting a proper representation of the variables with labeled values.
n = "GeeksforGeeks"
f = 2009
p = True
with open('output.txt', 'w') as file:
file.write("Website Name: " + str(n) + '\n')
file.write("Founded Year: " + str(f) + '\n')
file.write("Is Popular: " + str(p) + '\n')
Output
website_name = 'GeeksforGeeks'
founded_year = 2009
is_popular = True
Related Articles: