user5505459
user5505459

Reputation:

My python function won't write to a file

I've made a function for a flask application to create a decorator and a function and then write them to a file but when I run it, it doesn't create a file and write to it and it doesn't return any errors.

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

Upvotes: 0

Views: 90

Answers (2)

user5460786
user5460786

Reputation:

I would use philhag answer but use %s instead of %r or you'll write a string, and you could use .name if you want to use the function more than once(Which you probably do).

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

Upvotes: 1

phihag
phihag

Reputation: 287755

A return statement terminates execution of the function, so any code after it is ignored. Also, write writes a string, not random objects. You want:

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

Upvotes: 3

Related Questions