Working with text file in python – copy vertical text and paste it horizontally

Question:

How to copy vertical text and paste it horizontally as csv.

input_text_file = """
Statement 1
some text
some text
some text
some text
some text
some text
some text
Statement 2
some text
some text
some text
some text
some text
some text
Statement 3
some text
some text
some text
some text
some text
some text
some text
some text
some text
some text
some text
Statement 4
some text
some text
some text
some text
some text
some text
some text
some text
...........
"""

Check if the line starts with Statement, copy everything till the next line that starts with Statement and paste it horizontally as csv (comma separated).

Not all the Statements have the same number of lines.

with open('input_text_file', 'r') as intext:
    for line in intext:
        if line.startwith('Statement'):
            continue till the next line.startwith('Statement')
            ..........


with open('output_csv_file', 'w') as csvfile:
    write to csv file


output_csv_file ="""
Statement 1,Statement 2,Statement 3,Statement 4
some text  ,some text  ,some text  ,some text  
some text  ,some text  ,some text  ,some text  
some text  ,some text  ,some text  ,some text  
some text  ,some text  ,some text  ,some text  
some text  ,some text  ,some text  ,some text  
some text  ,some text  ,some text  ,some text  
some text              ,some text  ,some text
                       ,some text  ,some text
                       ,some text
                       ,some text
                       ,some text
"""

How to achieve this in python?

Asked By: new_py

||

Answers:

Use the following iterative approach with csv.writer:

import csv

with StringIO(input_text_file) as f, open('result.csv', 'w') as out:
    d = {}

    for row in f:
        row = row.strip()
        if row:
            if row.startswith('Statement'):  # capture key/column name
                key = row
                d[key] = []
            else:
                d[key].append(row)
                
    writer = csv.writer(out)
    writer.writerow(d.keys())  # write header
    writer.writerows(zip(*d.values()))

result.csv contents:

Statement 1,Statement 2,Statement 3,Statement 4
some text,some text,some text,some text
some text,some text,some text,some text
some text,some text,some text,some text
some text,some text,some text,some text
some text,some text,some text,some text
some text,some text,some text,some text
Answered By: RomanPerekhrest
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.