0

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>
1

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

is there any possible substitute for import os?? Such as import pathlib / from Path import pathlib??
Or basically, a way that does not require the import os module?
@carson, yeah I just checked and it seems to be possible. I just always have trusted the "os" module, that's all. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.