How can I close files for writing within a loop

Now let’s say there is some reason that you really did need all those files open at the same time.

const outpath = "/some/path"

function main()
    out_loc = [5.0, 10.0, 15.0, 20.0, 25.0] # This will change based on what the user wants
    
    # open each file, and write a header
    # i is just counting, 1, 2, 3, ...
    # o is now the values in out_loc
    for (i, o) in enumerate(out_loc)
        # no do syntax
        f[i] = open(joinpath(outpath,"time_series_depth_$o_km.out")), "w")
        write(f[i], "t slip sliprate shear_stress state")
    end

    try
        t = 0
        slip = 0
        shear_stress = 0
        state = 0
        while t < tmax
            # I am very confused about what might be happening in this loop
            for (i,o) in enumerate(out_loc)
                t, slip, sliprate, shear_stress, state = perform_time_step(o, t, slip, shear_stress, state)
                println(f[i], "$t $slip $sliprate $shear_stress $state")
            end
        end
    finally
        # close each file
        for i in 1:length(f)
            close(f[i])
        end
    end
end
2 Likes