Convert single column txt file to multi column csv

31 Views Asked by At

I have a txt file with data in the following structure

Ident
Name
Value A
Value B
Value C
Ident 
Name
Value A
Value B
Value C
...

How can I convert this to a csv file in the following structure if I know the amount of columns needed and can ensure that the text file has for all Idents the same amount of values?

Ident;Name;Value A;Value B;Value C;
Ident;Name;Value A;Value B;Value C;

I guess this is very simple but I was not able to find anything. Code language can be any (bash, python etc.)

1

There are 1 best solutions below

0
LNTR On

Let's say you have your text like the one on your question,

text = """
Ident
Name
Value A
Value B
Value C
Ident
Name
Value A
Value B
Value C
"""

You can split all of those cell values into a list. Create a row list according to the column count. And join all the rows on the row list with "\n" character.

Steps

  1. Splitting each cell value and putting them into a list

    old_delimiter = "\n"
    new_delimiter = ";"
    
    column_count = 5
    
    cell_list = text.strip().split(old_delimiter)  
    
  2. Creating a function to combine each cell value into a new row

    def combine_cells_into_row(cell_start_index):
        column_values = cell_list[cell_start_index : cell_start_index + column_count]
        row = f"{new_delimiter}".join(column_values) + new_delimiter
        return row
    
  3. Generating all the rows

    rows = map(combine_cells_into_row,range(0, len(cell_list), column_count))
    
  4. Then combine generated rows using join.

    output = "\n".join(rows) 
    
    print(output)