How to write the output from previous cell to a csv file?

I would like to know how I can write the output from the previous cell to a csv file?

IPython/Jupyter magics can help you here. Specifically, the ones I suggest using are documented here and here. (Succinct coverage of the use of %store here.)

Add above first line of the previous cell the following cell magic as a line:

%capture out

Then run your previous cell.

Now in the cell below that to save the captured output from that previous cell:

# write the captured stdout channel to a file
%store out.stdout >my_data.csv

Optionally, if you want what would have been the output from the cell where you added the %%capture magic to appear in the notebook as well, add a cell above or below where you used %store, with the following contents:

# show here the content from captured stdout channel 
sys.stdout.write(out.stdout)

print(out.stdout) seems to work as well.
The basis for out.stdout being the way to invoke is described here.

Alternatively, you could use %load my_data.csv after the %store command to show the contents of the saved file in the notebook.


The capture approach can be used for rich output as well, see use with plots here.


For the sake of completeness, I’ll add there is also the following method for IPython.utils.capture.CapturedIO:

out.show()

(out.show() can be replaced with out())
The documentation here makes it seem like that would be a reasonable way to also display the captured results in the notebook; however, for some reason, at present showing out those ways in the notebook also appends an additional line that is the count of the number of characters in the output string shown above. (This seems less than ideal to me. However, maybe I am missing something why someone using the show() method would want that or if it is the result of some other notebook property adding that line. It doesn’t seem to happen with rich outputs, see here, and maybe it is because this is a stdout channel object in this example.)

1 Like

Thank you very much for your explanation.