user5208585
user5208585

Reputation:

Write function to a new file Python 3

how can I write a function in a new file in Python IE:

def fun_one(x):
    print(x)
file_handler = open('file.py','a')
file_handler.write(fun_one)
file_handler.close()
quit()

Upvotes: 0

Views: 70

Answers (1)

grovina
grovina

Reputation: 3077

Use inspect:

import inspect


def fun_one(x):
    print(x)

with open('file.py', 'a') as f:
    f.write(inspect.getsource(fun_one))

Your file.py will contain:

def fun_one(x):
    print(x)

Also, note that you don't need quit() and that you can open and close the file using with.

That being said, I remain curious about why you would need such thing.

Upvotes: 1

Related Questions