【问题标题】:Why Python returns error "a float is required" while writing to file?为什么 Python 在写入文件时返回错误“需要浮点数”?
【发布时间】:2017-02-07 13:06:12
【问题描述】:

我正在尝试从数据库创建具有 id 的文件并插入一些文本,但它仍然不想让我这样做。

self.a.execute(
    """INSERT INTO serial (serial.Name, Description, GenreID, CreationDate) VALUES (%s, %s, %s, %s)""",
       (title, overview, genre, release_date))
self.a.execute("""SELECT id, serial.Name FROM serial WHERE Name=%s""", title)

title = str(self.a.fetchall()[0]['id'])

with open("templates/serials/" + title + '.html', 'w+') as o:

o.write("""
        {% extends '../base.html' %}
        {% block content %}
        <p>%s</p>
        {% endblock %}
        """ % (title))

如果我把%(title)放在写函数之后,它会返回unsupported operand type(s) for %: 'int' and 'str'

【问题讨论】:

    标签: python file api flask themoviedb-api


    【解决方案1】:

    当使用旧式字符串格式时,“%”具有给定的含义,因此如果您想在格式字符串中添加一个字面“%”,则必须将其(连同其自身)转义,即:

    o.write("""
        {%% extends '../base.html' %%}
        {%% block content %%}
        <p>%s</p>
        {%% endblock %%}
        """ % (title))
    

    【讨论】:

    • 这帮助最大。
    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    相关资源
    最近更新 更多