Icon

kn_​example_​python_​text_​fixed_​width

export data to a fixed width text file with KNIME and Python

export data to a fixed width text file with KNIME and Python

export data to a fixed width text file with KNIME and Pythonhttps://forum.knime.com/t/export-data-to-a-pre-defined-fixed-width-format/65185/2?u=mlauber71 import knime.scripting.io as knioimport pandas as pddf = knio.input_tables[0].to_pandas()# Determine the maximum width for each column based on the contentscolumn_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 DataFramecolumn_widths_df = pd.DataFrame(list(column_widths.items()), columns=['Column', 'Width'])# Format the DataFrame as a fixed-width stringformatted_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 filewith open(var_path_export_file, 'w') as file: file.write(formatted_df)knio.output_tables[0] = knio.Table.from_pandas(column_widths_df) locate and create/data/ folderwith absolute pathsoutput_1.txtknime://knime.workflow/data/output_1.txtoutput_1.txt Collect LocalMetadata Data Generator Python Script Fixed WidthFile Reader File Reader(Complex Format) export data to a fixed width text file with KNIME and Pythonhttps://forum.knime.com/t/export-data-to-a-pre-defined-fixed-width-format/65185/2?u=mlauber71 import knime.scripting.io as knioimport pandas as pddf = knio.input_tables[0].to_pandas()# Determine the maximum width for each column based on the contentscolumn_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 DataFramecolumn_widths_df = pd.DataFrame(list(column_widths.items()), columns=['Column', 'Width'])# Format the DataFrame as a fixed-width stringformatted_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 filewith open(var_path_export_file, 'w') as file: file.write(formatted_df)knio.output_tables[0] = knio.Table.from_pandas(column_widths_df) locate and create/data/ folderwith absolute pathsoutput_1.txtknime://knime.workflow/data/output_1.txtoutput_1.txtCollect LocalMetadata Data Generator Python Script Fixed WidthFile Reader File Reader(Complex Format)

Nodes

Extensions

Links