Printing to file inside loop

Usually I print to a file if the request gets an KO (using session status) like this

exec((session: io.gatling.core.session.Session) => {
if (session.status == KO) {
writer2.println(session.attributes.seq(“pid”))
}
session
})

But I want to print to a file inside a loop (being the same session) like this:

.repeat(20) {

feed(csv(“data/pid.csv”).random)

/* If loop.increment is KO then print to file*/

Is there a way to achieve this?