I am trying to use Python to write to a file. However, the code has multiple " in it plus calls a variable. I simply cannot manage the syntax.
The code should result in:
{
"Name of site": "https://.google.com",
Where the website is a variable not a string.
The code attempt is below. It never resolves the variable and just displays it as a string called host_name. I have attempted to add backslashes and quotations (various types of single and double) but whatever I try does not work.
with open ("new_file.txt", "a") as f:
f.write ("{ \n")
f.write("\"Name of site\": \"https://" + host_name + ", \n")
The new_file.txt shows:
"Name of site": "https:// + host_name + "\," + "
I have no idea where the "\," comes from.
You can use f strings, and take advantage of the fact that both
''and""create string literals.Note that in that example you have to also concatenate strings in order to avoid the fact that f-strings don't allow either braces or backslashes; however, there is even a way around that.
So that's how you'd build the string directly. But it does also seem more likely that what you really want to is to construct a dictionary, then write that dictionary out using JSON.