Received ValueError: I/O operation on closed file but the data printed well

  pandas, python, python-3.x, sys

The data printed well according to the looping I make but I received File I/O error after it finish written on txt. I didnt indent all_true because it calculate total value. Can anybody tell whats wrong and why the system throws value i/o error?

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)


    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)

Source: Python Questions