如何读取使用python创建html的变量

如何读取使用python创建html的变量,python,Python,我用python写的 Name = input("type the Name: ") Last_Name = input("Type the lastname: ") ID = input("Type the ID: ") folder = "c:\\xfiles" if os.path.exists(folder) == False: os.mkdir(folder) html = open(folder+"\\"+"Homework"+".html", "w") html.write('&l

我用python写的

Name = input("type the Name: ")
Last_Name = input("Type the lastname: ")
ID = input("Type the ID: ")
folder = "c:\\xfiles"
if os.path.exists(folder) == False:
os.mkdir(folder)
html = open(folder+"\\"+"Homework"+".html", "w")
html.write('<html>')
html.write('    <head>')
html.write('    </head>')
html.write('    <body>')
html.write('        <center>')
html.write('            <table border=10 cellspacing=0 cellspacing=2>')
html.write('                <tr>')
html.write('                    <td>ID:</td>')
html.write('                    <td>ID</td>') #Here trying to call but it just show me "ID"
html.write('                </tr>')
html.write('        </center>')
html.write('    </body>')
html.write('</html>')
html.close()
Name=input(“键入名称:”)
Last_Name=输入(“键入lastname:”)
ID=输入(“键入ID:”)
folder=“c:\\X文件”
如果os.path.exists(folder)=False:
os.mkdir(文件夹)
html=打开(文件夹+“\\”+“作业”+“.html”,“w”)
html.write(“”)
html.write(“”)
html.write(“”)
html.write(“”)
html.write(“”)
html.write(“”)
html.write(“”)
write('ID:')
write('ID')#此处尝试调用,但它只显示“ID”
html.write(“”)
html.write(“”)
html.write(“”)
html.write(“”)
html.close()

当我尝试调用变量“ID”时,它不会出现,没有任何原因或任何帮助来解决这个问题?

您必须使用类似于格式的东西将变量放入字符串中,以便它显示出来。使用类似于原始方法的方法,您必须改变这一点:

html.write('                    <td>%s</td>' % ID) #"ID" now using the variable
html.write(“%s”%ID)#“ID”现在使用变量
但是,如果您正在制作一个HTML模板,那么我假定您想要替换一组不同的字符串。必须一行一行地一直这样做会让人非常恼火,因此我建议做一些类似的事情,以使流程更易于管理:

first_name = input("type the Name: ")
last_name = input("Type the lastname: ")
ID = input("Type the ID: ")

template = """<html>
    <head>
    </head>
    <body>
        <center>
            <table border=10 cellspacing=0 cellspacing=2>
                <tr>
                    <td>ID:</td>
                    <td>{ID}</td> <-- Now we are actually accessing the variable here
                </tr>
        </center>
    </body>
 </html>
""" 
context = {
 "first_name": first_name, 
 "last_name": last_name,
 "ID": ID,
 } 
with  open('homework.html','w') as myfile:
    myfile.write(template.format(**context))
first\u name=input(“键入名称:”)
last_name=输入(“键入lastname:”)
ID=输入(“键入ID:”)
模板=“”“
身份证件:

{ID}更改代码中的这一行。您将ID作为字符串写入html文件,而不是ID的值

html.write('                    <td>'+ID+'</td>') #it prints the value of ID
html.write(“”+ID+“”)#它打印ID的值

last和name之间怎么会有空格..应该是last\u name您使用的是哪个python版本?我使用的是3.4.0version@user3691177:那么会发生什么?您是否收到异常,was
{ID}
写入文件而不是输入的id?我更正了答案中的一些名称错误,但如果您提到这一点,可能会有所帮助。请使用
%s
字符串插值或
.format()