Export data to a pre-defined fixed width format

Just starting on the Data Wrangler path with Knime. I am looking to read from various data sources (Access, Excel, multiple DBs, positional flat files, etc.) and ultimately write the specific data nodes in a custom positional text file.

I noticed that Knime does have a positional file reader yet does not have a positional file writer. Is it possible to create a custom text file writer? Export to CSV is not an option.

Raul

1 Like

@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

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.