Search code examples
pandascsvnotepad

Save lines of txt file into csv


I have a txt file that looks like this

a,b,c
0,0,0
0,0,0
*
x,y,z
1,1,1
1,1,1
*
u,v,w
9,9,9
9,9,9
*

I would like to save every three lines excluding the asterisk into csv files so my csv files look like this.

0.csv

a,b,c
0,0,0
0,0,0

1.csv

x,y,z
1,1,1
1,1,1

2.csv

u,v,w
9,9,9
9,9,9

Is there any efficient way to do this? Thank you so much.


Solution

  • You can use itertools.groupby to "split" the file into separate groups:

    from itertools import groupby
    
    with open("your_file.txt", "r") as f_in:
        i = 0
        for is_asterisk, lines in groupby(f_in, lambda line: line.strip() == "*"):
            if not is_asterisk:
                print("Writing {}.csv".format(i))
                with open("{}.csv".format(i), "w") as f_out:
                    f_out.writelines(lines)
                i += 1
    

    Prints:

    Writing 0.csv
    Writing 1.csv
    Writing 2.csv
    

    and saves the files.