Reputation: 8837
I would like to be able to save the TEXT output of an iPython notebook cell into a file on disk.
I have 2 additional requirements/requests:
I have figured out how to use the %%capture
magic for some basic saving of an iPython notebook's cell into a file, but it does not seem flexible enough: it keeps appending every time I re-run the cell and I cannot get it to display within the same cell.
Here is what I have so far:
%%capture cap --no-stderr
print 'stuff'
with open('output.txt', 'w') as f:
f.write(cap.stdout)
# clear the cap by deleting the variable here?
# del cap
When I try to put cap.show()
after the write, it does not seem to display. Instead, it puts the output into the cap variable twice.
Upvotes: 46
Views: 96678
Reputation: 602
%%capture cap
captures different outputs of the current cell (depending on --no-stderr, --no-stdout, or --no-display options) and stores them in cap
.
The capture object cap
is only created/updated at the end of the cell execution. To display its content, using cap()
(same as cap.show()
), or save it to a file, you have to do it in another cell.
In a first cell, cap
is filled with output contents, and in a second cell cap
content is saved and displayed:
%%capture cap
del cap # delete previously existing cap variable
print("capture me if you can!")
with open('output.txt', 'w') as f:
f.write(cap.stdout)
cap()
capture me if you can!
When %%capture cap
, cap.stdout
, and cap.show()
are all in the same cell:
%%capture cap
del cap # delete previously existing cap variable
print("capture me if you can!")
with open('output.txt', 'w') as f:
f.write(cap.stdout)
cap()
it raises a NameError: name 'cap' is not defined
error.
If it does not raise an error, that means that you had already initialized cap
with some data (maybe running the very same cell but without the cap.output
and cap.show()
).
In that case, that means that by adding cap.show()
at the end of your cell, you add the content of cap
to the outputs of this cell, so, you override cap
content with "the new output of the cell + the previous content of cap
".
As a result, the next time you will run the cell it will write in your file the previous "new output of the cell + previous content of cap
".
Note that, in the examples above, the del cap
is just here to raise errors when cap
is called in the %%capture cap
cell. This del cap
is not necessary for normal use: cap
's content is fully replaced when %%capture cap
is called.
Upvotes: 2
Reputation: 11
%%capture cap --no-stderr
print("a")
with open('output.txt', 'w') as f:
f.write(str(cap))
Upvotes: 1
Reputation: 20456
You have a typo, missing d
in cap.stout
. It should be cap.stdout
I tested the following and it worked fine. cap.show()
also printed "stuff" and re-running the cell overwrote the file.
%%capture cap --no-stderr
print 'stuff'
with open('output.txt', 'w') as f:
f.write(cap.stdout)
Upvotes: 42