0

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.

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

5 Comments

I wouldn't want to import another library just to export csv.
added an option without any library too
This works perfect. I'm not sure why my code didn't work. Do you have any clue?
Your string is already separated with lines but you are also doing for r in output.splitlines():. I thing the splitlines here is splitting the string further into single characters? If you just loop over output without splitlines, it should work too.
One more thing... if you are using with open...., you don't need to close the file as it will happen itself after the with context is over.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.