Home > Net >  How should I put python inputs when I create html file in python?
How should I put python inputs when I create html file in python?

Time:06-10

from email import message

def main(): # Creates a main function to initiate the program
    global name, info
    
    name = input("Enter your name: ") # Makes inputs that requires an user to enter info
    info = input("Describe yourself: ")
    
main() # The program starts here

f = open('test3.html','w')

message = """<html>
<head>
</head>
<body>
<center>
<h1>{name}</h1>
</center>
<hr />
{info}
<hr />
</body>
</html>"""

f.write(message)
f.close()

Hello, I am creating a py file that accepts the user's inputs (which are {name} and {info} in my code) and creates a .html file. I tried to use name or info but both not worked. Are there any other ways that I can use to make it work correctly? Thank you so much for reading my question

CodePudding user response:

Use an f string

from email import message

def main(): # Creates a main function to initiate the program
    global name, info
    
    name = input("Enter your name: ") # Makes inputs that requires an user to enter info
    info = input("Describe yourself: ")
    
main() # The program starts here

f = open('test3.html','w')

# add 'f' before the first quotation mark
message = f"""<html>
<head>
</head>
<body>
<center>
<h1>{name}</h1>
</center>
<hr />
{info}
<hr />
</body>
</html>"""

f.write(message)
f.close()

You probably also want to refactor your code to look like this:

from email import message

def main(): # Creates a main function to initiate the program
  name = input("Enter your name: ") # Makes inputs that requires an user to enter info
  info = input("Describe yourself: ")

  with open('test3.html', 'w') as f:
    body = f"""<html>
<head>
</head>
<body>
<center>
<h1>{name}</h1>
</center>
<hr />
{info}
<hr />
</body>
</html>"""
    f.write(body)

if __name__ == "__main__":
  main()

In the original, you imported message, but then overrode that import by assigning a variable with that same name, so this new version fixes that (though message is now an unused import, unless this isn't the entire code file)

CodePudding user response:

You can solve it through %()s

name = "CN-LanBao"
info = "vote"
message = """
<html>
<head>
</head>
<body>
<center>
<h1>%(name)s</h1>
</center>
<hr/>
%(info)s
<hr/>
</body>
</html>
""" % dict(name=name, info=info)

with open('test3.html', 'w') as f:
    f.write(message)

Attach HTML content

<html>
<head>
</head>
<body>
<center>
<h1>CN-LanBao</h1>
</center>
<hr/>
vote
<hr/>
</body>
</html>
  • Related