[英]My python function won't write to a file
我为烧瓶应用程序创建了一个函数,以创建装饰器和函数,然后将其写入文件,但是当我运行它时,它不会创建文件并写入文件,并且不会返回任何错误。
def make_route(title):
route = "@app.route(/%s)" %(title)
def welcome():
return render_template("%s.html" %(title))
return welcome
f = open('test1.txt', 'w')
f.write(route, '/n', welcome, '/n')
f.close()
make_route('Hi')
return
语句终止该函数的执行,因此忽略该函数之后的所有代码。 另外, write
写一个字符串,而不是随机对象。 你要:
def make_route(title):
route = "@app.route(/%s)" %(title)
def welcome():
return render_template("%s.html" %(title))
with open('test1.txt', 'w') as f:
f.write('%r\n%r\n' % (route, welcome))
return welcome
make_route('Hi')
我将使用philhag答案,但使用%s代替%r,否则您将编写一个字符串,并且可以使用。 如果您想多次使用此功能,请命名 (您可能会使用)。
def make_route(title):
route = "@app.route('/%s')" %(title)
def welcome():
return render_template("%s.html" %(title))
with open('test2.py', 'w') as f:
f.write('%s\n%s\n' % (route, welcome))
welcome.__name__ = title
return welcome
make_route('Hi')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.