Reputation: 3984
Suppose I have a csv file with 4 columns per row like this:
712,713,714, 26 blah blah
I want to have the result like this :
712 26 blah blah
713 26 blah blah
714 26 blah blah
Now I would read the csv file in python but how would I split the rows like that without changing other columns and then write the result into another csv file.
p.s- I don't know pandas so I would use simple csv module
Upvotes: 0
Views: 1435
Reputation: 92894
Straightforwardly with csv.reader
and csv.writer
objects:
Sample test.csv
:
712,713,714, 26 blah blah
1,2,3, 11 aaa bbb
import csv
inp_fname = 'test.csv'
out_fname = 'transposed.csv'
with open(inp_fname, 'r', newline='') as in_csvfile, \
open(out_fname, 'w', newline='') as out_csvfile:
reader = csv.reader(in_csvfile, delimiter=' ', skipinitialspace=True)
writer = csv.writer(out_csvfile, delimiter='\t')
for row in reader:
for v in row[0].rstrip(',').split(','):
writer.writerow([v] + row[1:])
The final transposed.csv
file contents:
712 26 blah blah
713 26 blah blah
714 26 blah blah
1 11 aaa bbb
2 11 aaa bbb
3 11 aaa bbb
Upvotes: 2