收到 ValueError:对关闭的文件进行 I/O 操作,但数据打印良好

问题描述

根据我所做的循环打印的数据很好,但在完成写入 txt 后收到文件 I/O 错误。我没有缩进 all_true 因为它计算总值。谁能告诉我出了什么问题,为什么系统会抛出 value I/O 错误

错误文件“C:\Users\User\anaconda3\lib\site-packages\ipykernel\kernelbase.py”,第 277 行,在 dispatch_shell sys.stdout.flush() 中

ValueError: 关闭文件I/O 操作。

import sys

with open('testing.txt','w') as f:
  sys.stdout = f
  for i in range(len(train_idx)):
    training_data,testing_data = dataset.iloc[train_idx[i]],dataset.iloc[test_idx[i]]
    tree = CART(training_data,training_data,training_data.columns[:-1])

    y_pred = test(testing_data,tree)
    y_true = testing_data["class"]

    y_pred = np.array(y_pred).astype(str)
    y_true = np.array(y_true).astype(str)

    all_true.append(list(y_true))
    all_pred.append(list(y_pred))

    print("----------------- Fold {} --------------".format(i+1))

    # calculate precision,recall and f1-score
    calculate_metrics(y_true,y_pred)

    # plot confusion matrix
    plot_confusion_matrix(y_true,y_pred)

  all_true = [v for item in all_true for v in item]
  all_pred = [v for item in all_pred for v in item]

  calculate_metrics(all_true,all_pred)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)