Saving the output of a cell in jupyter notebook with a new line after each number

时光毁灭记忆、已成空白 提交于 2019-12-31 05:46:07

问题


I saved output of a cell as a txt file as follows:

First cell:

%%capture cap --no-stderr
print(q)

Second cell:

with open('output.txt', 'w') as f:
    f.write(cap.stdout)

Below is a small piece of code that I wanted to save:

#%%
np.seterr(over='ignore')

a = np.uint32(1664525)
c = np.uint32(1013904223)
seed = np.uint32(1)

rng = LCG(seed, a, c)
q = [rng.next() for _ in range(0, 2500000)]

The file is saved, however the generated numbers are separated by a comma, but I want each generated number to be separated by a new line, not a comma

I tried to change "w" to "a" and add "\ n" as below but it does not work for me.

with open('output.txt', 'a') as f:
    f.write("\n")

回答1:


%%capture capture all the out of the code beside it in this cell, so you can print out all the elements from the list.

%%capture cap --no-stderr
for i in q:
    print(i)

with open('output.txt', 'w') as f:
    f.write(cap.stdout)

cap.stdout handle what %%capture captured as a whole, so when you tried to add \n, it won't work.

Is it what you want?



来源:https://stackoverflow.com/questions/57112535/saving-the-output-of-a-cell-in-jupyter-notebook-with-a-new-line-after-each-numbe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!