【问题标题】:Received ValueError: I/O operation on closed file but the data printed wellReceived ValueError: I/O operation on closed file but the data print well
【发布时间】:2021-01-14 09:44:15
【问题描述】:

根据我制作的循环,数据打印良好,但在完成写入 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)

【问题讨论】:

    标签: python python-3.x pandas sys


    【解决方案1】:

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

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

    【讨论】:

    • 仍然收到相同的错误,并且二进制文件甚至没有写入数据
    • 写完后尝试关闭文件:testing.txt.close()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 2021-03-02
    相关资源
    最近更新 更多