Here
https://stackoverflow.com/questions/33178514/how-do-i-save-print-statements-when-running-a-program-in-slurm , multiple methods to print and save (write) in a file immediately even during a loop in Python. One of them (by Manu) worked for me (inside a Python loop in slum job).
import builtins
import os
import sys
def printsync(text):
builtins.print(text)
os.fsync(sys.stdout)
sys.stdout = open(output_file, 'w', buffering=1)
for j in range(1000):
printsync('Immediate output', j)