Export data to a pre-defined fixed width format

@rjmendezii welcome to the KNIME forum. You could employ the bundled Python of KNIME to export data dynamically to a TXT file with fixed width:

import knime.scripting.io as knio
import pandas as pd

df = knio.input_tables[0].to_pandas()

# Determine the maximum width for each column based on the contents
column_widths = {col: max(df[col].apply(lambda x: len(str(x))).max(), len(col)) + 2 for col in df.columns}

# Export the column_widths to a DataFrame
column_widths_df = pd.DataFrame(list(column_widths.items()), columns=['Column', 'Width'])

# Format the DataFrame as a fixed-width string
formatted_df = df.to_string(index=False, col_space=column_widths, justify='left')

var_path_export_file = knio.flow_variables['context.workflow.data-path'] + 'output_1.txt'

# Write the formatted DataFrame to a text file
with open(var_path_export_file, 'w') as file:
    file.write(formatted_df)

knio.output_tables[0] = knio.Table.from_pandas(column_widths_df)

kn_example_python_text_fixed_width.knwf (131.2 KB)

2 Likes