I'm using following script (Python 3) with the intention to
- apply a function row by row and
- write each resulting line into a csv.
More precisely, I just like to append each row to the existing file.
Code:
with open('file.csv', 'a') as f:
df['newcolumn'] = df.apply(some_function, axis=1, result_type='expand')
df.to_csv(f, mode='a', header=f.tell()==0, encoding='utf-8', index=False)
The issue with this code: Apparently, the script does not write line by line into the *.csv, but only creates the full csv when all lines are computed. For any error in the script, this implies that it ends up with zero content.
How can I re-write the script so that the file.csv is updated in every step, and not empty until completion?
Thank you!