我的python函数赢了';不要写入文件

我的python函数赢了';不要写入文件,python,Python,我为一个flask应用程序创建了一个函数来创建一个装饰器和一个函数,然后将它们写入一个文件,但当我运行它时,它不会创建一个文件并写入其中,也不会返回任何错误 def make_route(title): route = "@app.route(/%s)" %(title) def welcome(): return render_template("%s.html" %(title)) return welcome f = open('test1.

我为一个flask应用程序创建了一个函数来创建一个装饰器和一个函数,然后将它们写入一个文件,但当我运行它时,它不会创建一个文件并写入其中,也不会返回任何错误

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')
终止函数的执行,因此忽略它之后的任何代码。另外,
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')
终止函数的执行,因此忽略它之后的任何代码。另外,
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 answer,但使用%s而不是%r,否则您将编写一个字符串,如果您想多次使用该函数(您可能会这样做),您可以使用。name


我将使用philhag answer,但使用%s而不是%r,否则您将编写一个字符串,如果您想多次使用该函数(您可能会这样做),您可以使用。name


看起来您在写入文件之前返回。
return
停止函数的执行,因此之后的所有内容都不会执行。看起来您在写入文件之前返回。
return
停止函数的执行,因此之后的所有内容都不会执行。只是好奇而已(这可能更针对OP,因为它是他最初编程的方式),但函数中函数的用途是什么?Doe sit实际上被调用了两次,我怀疑是这样的(一次在初始写入结束时,一次在返回
make\u路由时function@Madivad是的,它会被再次使用,它是用来与flask建立url路由的,当有人访问url时,它会被再次调用。感谢phihag的帮助。只是好奇而已(这可能更针对OP,因为它是他最初编程的方式),但函数中函数的用途是什么?Doe sit实际上被调用了两次,我怀疑是这样的(一次在初始写入结束时,一次在返回
make\u路由时function@Madivad是的,它会被再次使用,它是用来与flask建立url路由的,当有人访问url时,它会再次被调用。感谢phihag的帮助。