问题描述
我将单元格的输出保存为txt文件,如下所示:
I saved output of a cell as a txt file as follows:
第一个单元格:
%%capture cap --no-stderr
print(q)
第二个单元格:
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
我尝试将"w"更改为"a"并按如下所示添加"\ n",但这对我不起作用.
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")
推荐答案
%%capture
在此单元格中捕获其旁边所有代码,因此您可以打印出列表中的所有元素.
%%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
处理整个%%capture
捕获的内容,因此当您尝试添加\n
时,它将无法正常工作.
cap.stdout
handle what %%capture
captured as a whole, so when you tried to add \n
, it won't work.
是您想要的吗?
这篇关于在每个数字后用新行将单元格的输出保存在jupyter笔记本中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!