【问题标题】:Save the output of a cell in iPython notebook?在 iPython 笔记本中保存单元格的输出?
【发布时间】:2018-03-08 15:31:55
【问题描述】:

我的单元格 in[16] 中有一个 python 循环,它在每个循环中调用一个函数,并且该函数打印一堆字符串。 由于迭代次数很大(笔记本文件达到 99+ MB),我需要将这些字符串输出到不包含在 jupyter 文件中,而是输出到 txt 或 csv 文件中。 我已经阅读了这里提到的答案: how to save the output of a cell in iPython notebook?

但是,如果我使用该代码,我会收到以下粉红色错误消息:

ERROR:root:Line magic function %capture not found(但 cell magic %%capture 存在,你的意思是不是?)。

最终,还有这个错误消息: NameError: name 'cap' 未定义

所以只是给你一个例子。假设我有:

def test(i):
    print(i)


for i in range(1,10):
    test(i)

如何在 txt 文件而不是笔记本中导出/打印 1 到 10 的值? 老实说,我不是 python 专家,因此非常感谢您的帮助。

【问题讨论】:

    标签: save jupyter-notebook capture


    【解决方案1】:

    您的函数 def 打印在第一个单元格中... 然后在你的第二个单元格中:

    %%capture cap --no-stderr
    for i in range(1,5):
    test(i)
    

    在第三个单元格中:

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

    【讨论】:

      猜你喜欢
      • 2015-03-15
      • 1970-01-01
      • 2014-09-09
      • 2016-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-22
      • 1970-01-01
      相关资源
      最近更新 更多