I have a series of files with lots of variables defined in the form {myvar}
inside. eg
file.txt
This is {myvar}.
I want to open them, and have the variables being replaced normally:
with open('path/to/file.txt', 'r') as file:
myfile = file.read().replace('\n', '')
myvar='myself.'
print(f"{myfile}")
Should output:
This is myself.
How can I open the file as a formatted string? Or convert the string to formatted string?
This seems to work if the variable is local to the call, if it's a global variable, use **globals()
. You can also put the value in a dictionary that has the variable name as the key.
myvar = 'myself'
newline = '\n' # Avoids SyntaxError: f-string expr cannot include a backslash
with open('unformatted.txt', 'r') as file:
myfile = f"{file.read().replace(newline, '')}".format(**locals())
print(myfile)
You are almost there.
Assume there is "This is {myvar}." in file.txt.
Coding:
with open('path/to/file.txt', 'r') as file:
myfile = file.read().replace('\n', '')
myvar='myself'
print(myfile.format(myvar=myvar))
Any strings in plain text format, can be imported as a variable from a text file. Then the strings variable can be manipulated as normal.
In you case, the key is "{var}". So you can easily use ".format(var=varx) as long as you defined variable "varx".
Output:
This is myself.
And if you want to import html template with css style and replace some contents, you can just use "{{" and "}}" to escape "{" and "}".
Example 2 In file:
This is {myvar} for a {{var}}.
Output:
This is myself for a {var}.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.