为什么Python在写入文件时返回错误“需要浮点数”?(Why Python returns error “a float is required” while writing to file?)

系统教程 行业动态 更新时间:2024-06-14 16:54:47
为什么Python在写入文件时返回错误“需要浮点数”?(Why Python returns error “a float is required” while writing to file?)

我正在尝试使用数据库中的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'

I'm trying to create files with id from database and insert some text, but it still don't want to let me do it.

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

If i put %(title) after write function, it returns unsupported operand type(s) for %: 'int' and 'str'

最满意答案

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

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

When using old-style string formatting, "%" has a given meaning, so you have to escape it (with itself) if you want a litteral "%" in your format string, ie:

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

更多推荐

本文发布于:2023-04-08 12:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/1e8073c1983bfe6dc8f1642fd5a96e2c.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   文件   浮点数   returns   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!