If the goal is to calculate the correct column width, you have to do one pass through the data before writing the first row.
If the file can be read multiple times (not a UNIX stream), you can just read the file twice.
If the file is a stream, instead of retaining the entire dataset in memory, you can write to a temporary file and re-parse it after calculating the widths.