Home > Back-end >  convert text file column in csv row in python?
convert text file column in csv row in python?

Time:03-13

I have data.txt which look like this:

Ball    stump    inner   shocks
bat                      mask
gloves  helmet   grip   
pad     jersey   shoe    cap
1       5        9       13
2                        14
3       7        11  
4       8        12      16

from itertools import groupby, chain

with open("file.txt", "r") as fin,\
     open("file.csv", "w") as fout:
    for key, group in groupby(fin, key=lambda line: bool(line.strip())):
        if key:
            zipped = zip(*(line.rstrip().split() for line in group))
            fout.write(",".join(chain(*zipped))   "\n")

I want to convert this txt file into csv The output I would like see:enter image description here

  • Related