pandas 接收值错误:在关闭的文件上进行I/O操作,但数据打印良好

wkftcu5l  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(92)

根据我做的循环,数据打印得很好,但是在它完成写入txt后,我收到了文件I/O错误。我没有删除all_true,因为它计算总价值。有人能告诉我什么是错误的,为什么系统抛出值I/O错误吗?
错误:文件“C:\Users\User\anaconda 3\lib\site-packages\ipykernel\kernelbase.py”,行277,在dispatch_shell sys.stdout.flush()
ValueError:I/O operation on closed file.

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)

字符串

06odsfpq

06odsfpq1#

你间接地关闭了一个指向stdout的引用。with会自动关闭文件对象f,然后你将其设置为sys.stdout,因此它会被关闭。

with open('testing.txt', 'w') as f:
  stdout = sys.stdout
  sys.stdout = f
  ...
  ...
  # before the with statement ends.
  sys.stdout = stdout

字符串

ig9co6j1

ig9co6j12#

尝试以写入二进制模式打开文件。

with open('testing.txt', 'wb') as f:
...

字符串

相关问题