ValueError: I/O operation on closed file, flush()

ValueError: I/O operation on closed file, flush()

我有来自 https://towardsdatascience.com/training-your-own-message-suggestions-model-using-deep-learning-3609c0057ba8 的这段代码,我现在正在尝试。但是,我收到错误:target_similarity_matrix_file.flush() 上的“ValueError: I/O operation on closed file” 线。我该如何解决这个问题?我对 python 和 nlp 非常陌生,所以请保持温和。我之前没有这方面的经验,所以我无法排除故障。

with open('target_similarity_matrix.txt', 'w') as target_similarity_matrix_file:
for i in tqdm(range(len(target_texts))):
    neighbor_index, distances = targetAnnoyIndex.get_nns_by_item(i, len(target_texts), include_distances=True)

    target_similarity_row = [-1] * len(target_texts)
    for index in range(len(neighbor_index)):
        j = neighbor_index[index]
        target_similarity_row[j] = distances[index]
    
    
    target_similarity_matrix_file.write(str(target_similarity_row))
    if i != len(target_texts) - 1:
        target_similarity_matrix_file.write("\n")
        

target_similarity_matrix_file.flush()
target_similarity_matrix_file.close()

"With" 自动 close 并刷新文件,所以只需删除最后两行,文件已经 closed,你不需要 flush/close 它。 Close 已经刷新文件,当您在 os 缓存中有大量待处理的写入并且您希望它们在文件系统上时,通常使用文件刷新。