Reputation: 51
How can I create and append the output of my code to a txt file? I have a lot of code.
This is just a small example of what I'm trying to do:
def output_txt():
def blop(a,b):ans = a + b
print(ans)
blop(2,3)
x = 'Cool Stuff'
print(x)
def main(x):
f = open('demo.txt', 'a+')
f.write(str(output_txt))
f.close
main(x)
f = open('demo.txt', 'r')
contents = f.read()
print(contents)
But the output gives me this:
cool bananas<function output_txt at 0x0000017AA66F0F78><function output_txt at 0x0000017AA66F0B88><function output_txt at 0x0000017AA66F0948>
Upvotes: 2
Views: 23702
Reputation: 22827
If you just want to save the output of your code to a text file, you can add this to a Jupyter notebook cell (the variable result
holds the content you want to write away):
with open('result.txt', 'a') as fp:
fp.write(result)
If you want to convert your whole Jupyter notebook to a txt file (so including the code and the markdown text), you can use nbconvert. For example, to convert to reStructuredText:
jupyter nbconvert --to rst notebook.ipynb
Upvotes: 3