Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python parsing string to csv format

Tags:

python

I have a file containing a line with the following format

aaa=A;bbb=B;ccc=C

I want to convert it to a csv format so the literals on the equation sides will be columns and the semicolon as a row separator. I tried doing something like this

 f = open("aaa.txt", "r")
    with open("ccc.csv", 'w') as csvFile:
        writer = csv.writer(csvFile)
        rows = []
        if f.mode == 'r':
            single = f.readline()
            lns = single.split(";")
            for item in lns:
                rows.append(item.replace("=", ","))
            writer.writerows(rows)
            f.close()
            csvFile.close()

but I am getting each letter as a column so the result looks like :

a,a,a,",",A
b,b,b,",",B
c,c,c,",",C,"

The expected result should look like

aaa,A
bbb,B
ccc,C
like image 607
igx Avatar asked Mar 25 '26 02:03

igx


1 Answers

Just write the strings into the target file line by line:

import os
f = open("aaa.txt", "r")
with open("ccc.csv", 'w') as csvFile:
    single = f.readline()
    lns = single.split(";")
    for item in lns:
        csvFile.write(item.replace("=", ",") + os.linesep)
f.close()

The output would be:

aaa,A
bbb,B
ccc,C
like image 56
mutux Avatar answered Mar 27 '26 14:03

mutux