Reputation:
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
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