【问题标题】:Output user input to a file using variables使用变量将用户输入输出到文件
【发布时间】:2019-01-13 00:05:52
【问题描述】:

我正在尝试获取用户输入,例如 widgetName 的用户输入,并将其添加到进入 html 中 <title> 标记之间的文件的输出中。

我尝试查找如何做到这一点,但没有运气。

widgetName = input("Please enter the name you would like to use for your widget: ")

with open(os.path.join(widgetname, 'LockBackground.html'), 'w') as f:
    f.write("""
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title> USER INPUT GOES HERE!! </title>
<style type="text/css">
@font-face {
    font-family: HelveticaNeue-UltraLigCond;
    src: url('fonts/font-file-goes-here');
}

# More CSS goes here.
</style>
<script type="text/javascript" src="scripts/jquery-1.6.4.min.js"></script>
# More javascript here.
</head>
<body>

# Code goes here.

</body>
</html> """)

【问题讨论】:

  • 我建议谷歌搜索 “python 字符串格式”。有几种方法可以做到这一点。或者,更好的是,从The Python Tutorial 开始。它会教你所有你需要的基础知识。

标签: python file input


【解决方案1】:

你可以做两种方式。一种是使用%s字符串替换,另一种是使用{}

widgetName = input("Please enter the name you would like to use for your widget: ")

with open(os.path.join(widgetname, 'LockBackground.html'), 'w') as f:
    f.write("""
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>{}</title>
<style type="text/css">
@font-face {
    font-family: HelveticaNeue-UltraLigCond;
    src: url('fonts/font-file-goes-here');
}

    # More CSS goes here.
</style>
<script type="text/javascript" src="scripts/jquery-1.6.4.min.js"></script>
# More javascript here.
</head>
<body>

# Code goes here.

</body>
</html> """.format(widgetName))

另一种方式

widgetName = input("Please enter the name you would like to use for your widget: ")

with open(os.path.join(widgetname, 'LockBackground.html'), 'w') as f:
    f.write("""
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>%s</title>
<style type="text/css">
@font-face {
    font-family: HelveticaNeue-UltraLigCond;
    src: url('fonts/font-file-goes-here');
}

    # More CSS goes here.
</style>
<script type="text/javascript" src="scripts/jquery-1.6.4.min.js"></script>
# More javascript here.
</head>
<body>

# Code goes here.

</body>
</html> """ % widgetName) 

【讨论】:

  • 好答案。 Python 3.6+ 支持一种称为格式化字符串文字(或“f-string”)的东西——参见文档中的Formatted string literals,所以还有第三种方式——它们可能更容易使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多