I have a text file called help.txt which will be read and the contents printed out. I need the file to contain variable placeholders where the variable value will be substituted in, eg: ‘I have 3 variables: , and ‘ If this was just a string hard-coded in the python file I can treat it as an f string but I am unsure how to do this in an external file. I want the text to be in another file so that I can easily change it whenever I need to. Only I will have access to both the code and the text file.
Hi.. Welcome to SO, please include the code you have tried so far along with sample input & expected output.
2 Answers 2
If I understood you correctly you could just check the file as you read it in for these placeholders and replace them with your variable. Given ‘FileContents’ is the string you used to read in your file and ‘variable’ is the variable to replace it with, just use FileContents.replace(«», variable)
Thanks, works great. Should have thought of this lol. I used a dictionary to store all of the placeholders and the variables they represent and then just ran it through a for loop and works fine.
f-strings are effectively syntactic sugar for str.format with some fancy processing of the namespaces. You can achieve the same effect using str.format on the contents of the file. The advantage of doing that over str.replace is that you have access to the full power of the string formatting mini-language.
I would recommend storing all the legal replacements into a dictionary rather than attempting to use globals or locals . This is not only safer, but easier to maintain, since you can easily load the variables from a file that way:
Printing the file is now trivial:
with open('help.txt') as f: for line in f: print(line.format(**variables), end= '')
Best way to retrieve variable values from a text file?
Referring on this question, I have a similar -but not the same- problem.. On my way, I’ll have some text file, structured like:
var_a: 'home' var_b: 'car' var_c: 15.5
And I need that python read the file and then create a variable named var_a with value ‘home’, and so on. Example:
#python stuff over here getVarFromFile(filename) #this is the function that im looking for print var_b #output: car, as string print var_c #output 15.5, as number.
Is this possible, I mean, even keep the var type? Notice that I have the full freedom to the text file structure, I can use the format I like if the one I proposed isn’t the best. EDIT: the ConfigParser can be a solution, but I don’t like it so much, because in my script I’ll have then to refer to the variables in the file with
But what I’ll love is to refer to the variable directly, as I declared it in the python script. There is a way to import the file as a python dictionary? Oh, last thing, keep in mind that I don’t know exactly how many variables would I have in the text file. Edit 2: I’m very interested at stephan’s JSON solution, because in that way the text file could be read simply with others languages (PHP, then via AJAX JavaScript, for example), but I fail in something while acting that solution:
#for the example, i dont load the file but create a var with the supposed file content file_content = "'var_a': 4, 'var_b': 'a string'" mydict = dict(file_content) #Error: ValueError: dictionary update sequence element #0 has length 1; 2 is required file_content_2 = "" mydict_2 = dict(json.dump(file_content_2, True)) #Error: #Traceback (most recent call last): #File "", line 1, in #mydict_2 = dict(json.dump(file_content_2, True)) #File "C:\Python26\lib\json\__init__.py", line 181, in dump #fp.write(chunk) #AttributeError: 'bool' object has no attribute 'write'
In what kind of issues can I fall with the JSON format? And, how can I read a JSON array in a text file, and transform it in a python dict? P.S: I don’t like the solution using .py files; I’ll prefer .txt, .inc, .whatever is not restrictive to one language.
I would like to save variable (including its values) into a text file, so that the next time my program is opened, any changes will be automatically saved into the text file .For example:
balance = total_savings - total_expenses
How would I go about saving the variable itself into a text file instead of only its value? This section is for the register page
from tkinter import * register = Tk() Label(register, text ="Username").grid(row = 0) Label(register, text ="Password").grid(row = 1) e1 = Entry (register) e2 = Entry (register, show= "*") e1.grid(row = 0, column = 1) e2.grid(row = 1, column = 1) username = e1.get() password = e2.get() button1 = Button(register, text = "Register", command = register.quit) button1.grid(columnspan = 2) button1.bind("") import json as serializer with open('godhelpme.txt', 'w') as f: serializer.dump(username, f) with open('some_file.txt', 'w') as f: serializer.dump(password, f) register.mainloop()
from tkinter import * register = Tk() Label(register, text ="Username").grid(row = 0) Label(register, text ="Password").grid(row = 1) username = StringVar() password = StringVar() e1 = Entry (register, textvariable=username) e2 = Entry (register, textvariable=password, show= "*") e1.grid(row = 0, column = 1) e2.grid(row = 1, column = 1) button1 = Button(register, text = "Register", command = register.quit) button1.grid(columnspan = 2) button1.bind("") import json as serializer with open('godhelpme.txt', 'w') as f: serializer.dump(username.get(), f) with open('some_file.txt', 'w') as f: serializer.dump(password.get(), f)
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">write variable to a file in Python
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.