Search code examples
pythoncsvexport-to-csv

Python: How can I split the string properly to save in the format of csv?


I'm trying to save my string in the format of csv. The string looks like this, line separated by '\n',:

12,12,11,13,11,12
21,15,21,23,41,26
34,16,46,17,21,15
44,17,22,39,10,13

and so on. Also I have a manually written list of headers like

['A', 'B', 'C', 'D', 'E', 'F']

When I tried to write this using the csv writer,

with open('output.csv', 'w', newline='') as csvwriter:
    writer = csv.writer(csvwriter, dialect='excel')
    writer.writerow(header) # write header
    for r in output.splitlines():
        writer.writerows(r)
    csvwriter.close()

But when I look up the output file,

A,B,C,D,E,F
1
2
","
1
2
","
1
1
","
... (and so on)

Why this happens and how can I fix this? I appreciate any help.


Solution

  • if your string is like this:

    string = '''12,12,11,13,11,12
    21,15,21,23,41,26
    34,16,46,17,21,15
    44,17,22,39,10,13'''
    headers = ['A', 'B', 'C', 'D', 'E', 'F']
    

    without any library:

    with open('untitled.txt', 'w') as f:
        f.write(','.join(headers)+'\n')
        for line in string:
            f.write(line)
    

    You can make it into a pandas csv and then save:

    import pandas as pd
    data = []
    for i in string.split('\n'):
        data.append(i.split(','))
    csv = pd.DataFrame(data=data, columns=headers)
    
    csv.to_csv('path_to_save', index=False)