My question is, how do I take two different user input in Python and write them to an HTML file, so that when I open the file, it will display the user's input?
I am not looking to open the HTML file in the browser from Python. I just want to know how to pass Python input to the HTML file and how exactly that output must be coded into HTML.
This is the code:
name = input("Enter your name here: ")
persona = input("Write a sentence or two describing yourself: ")
with open('mypage.html', "r") as file_object:
data = file_object.read()
print(data)
I want to take the name input and persona input and pass it to a HTML file, open the file manually, and see it display as a webpage. The output would look something like this when I open the file:
<html>
<head>
<body>
<center>
<h1>
... Enter user name here... # in which i don't know how to print python user
# input into the file
</h1>
</center>
<hr />
... Enter user input here...
<hr />
</body>
</html>
-
Does this answer your question? Flask pass string to jinja?Umair Mubeen– Umair Mubeen2020年11月18日 20:54:41 +00:00Commented Nov 18, 2020 at 20:54
2 Answers 2
use format to add user input into html file
name = input("Enter your name here: ")
persona = input("Write a sentence or two describing yourself: ")
resut = """<html><head><body><center><h1>{UserName}</h1>
</center>
<hr />
{input}
<hr />
</body>
</html>""".format(UserName=name,input=persona)
print(resut)
Comments
The key feature here is to put some dummy text in the HTML file, which to be substituted:
mypage.html:
<html>
<head>
<body>
<center>
<h1>
some_name
# input into the file
</h1>
</center>
<hr />
some_persona
<hr />
</body>
</html>
Then the Python code will know exactly what to do like that:
import os
name = input("Enter your name here: ")
persona = input("Write a sentence or two describing yourself: ")
with open('mypage.html', 'rt') as file:
with open('temp_mypage.html', 'wt') as new:
for line in file:
line = line.replace('some_name', name)
line = line.replace('some_persona', persona)
new.write(line)
os.remove('mypage.html')
os.rename('temp_mypage.html', 'mypage.html')
3 Comments
Explore related questions
See similar questions with these tags.