Reputation: 2389
I have the following stringIO object:
s = io.StringIO("""idx Exam_Results Hours_Studied
0 93 8.232795
1 94 7.879095
2 92 6.972698
3 88 6.854017
4 91 6.043066
5 87 5.510013
6 89 5.509297""")
I want to transform it into a csv format and dump it into a new stringIO object. I'm using currently this strategy to do that, but to me it seems I bit clumsy.
output = ""
for line in s.getvalue().split('\n'):
output += re.sub(r'\s+',',',line) + '\n'
output = io.StringIO(output)
print(output.getvalue())
Result:
idx,Exam_Results,Hours_Studied
0,93,8.232795
1,94,7.879095
2,92,6.972698
3,88,6.854017
4,91,6.043066
5,87,5.510013
6,89,5.509297
Is there a clever way to achieve this ?
Upvotes: 0
Views: 1073
Reputation: 30050
You can try pandas
package
import io
import pandas as pd
s = io.StringIO("""idx Exam_Results Hours_Studied
0 93 8.232795
1 94 7.879095
2 92 6.972698
3 88 6.854017
4 91 6.043066
5 87 5.510013
6 89 5.509297""")
out = io.StringIO()
df = (pd.read_csv(s, delim_whitespace=True)
.to_csv(out, index=False, sep=';'))
print(out.getvalue())
idx;Exam_Results;Hours_Studied
0;93;8.232795
1;94;7.879095
2;92;6.972698
3;88;6.854017
4;91;6.043066
5;87;5.510013
6;89;5.509297
Upvotes: 1
Reputation: 13242
from io import StringIO
import csv
text = StringIO("""idx Exam_Results Hours_Studied
0 93 8.232795
1 94 7.879095
2 92 6.972698
3 88 6.854017
4 91 6.043066
5 87 5.510013
6 89 5.509297""")
output = StringIO('')
writer = csv.writer(output, delimiter=',')
writer.writerows(csv.reader(text, delimiter=' ', skipinitialspace=True))
print(output.getvalue())
Output:
idx,Exam_Results,Hours_Studied
0,93,8.232795
1,94,7.879095
2,92,6.972698
3,88,6.854017
4,91,6.043066
5,87,5.510013
6,89,5.509297
Upvotes: 1
Reputation: 6351
You can use the csv module:
import csv
from io import StringIO
s = StringIO(
"""idx Exam_Results Hours_Studied
0 93 8.232795
1 94 7.879095
2 92 6.972698
3 88 6.854017
4 91 6.043066
5 87 5.510013
6 89 5.509297"""
)
def convert(origin: str) -> StringIO:
si = StringIO(newline="")
spamwriter = csv.writer(
si, delimiter=",", quotechar="|", quoting=csv.QUOTE_MINIMAL
)
for line in origin.splitlines():
spamwriter.writerow(line.split())
return si
def main():
sio = convert(s.getvalue())
print(sio.getvalue())
if __name__ == "__main__":
main()
Upvotes: 1