根据我制作的循环打印的数据很好,但在完成写入txt后我收到文件I/O错误。我没有缩进 all_true 因为它计算总价值。谁能告诉我出了什么问题以及为什么系统会抛出值 I/O 错误?
错误:文件“C:\ Users \ User naconda3 \ 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)
尝试以写入二进制文件模式打开文件。
with open('testing.txt', 'wb') as f:
...
您间接关闭了指向 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