I'm trying to combine two lists into a csv, and have it output a line per each line of a second list.
a.csv
1
2
3
b.csv
a,x
b,y
c,z
Output:
c.csv
1|a|x
2|a|x
3|a|x
1|b|y
2|b|y
3|b|y
1|c|z
2|c|z
3|c|z
So for each line of "a" combine each line of "b", and get a list in "c".
Note, I have no need to separate "b" to reorder the columns, keeping the original order is fine.
A loop seems needed, but I'm having zero luck doing it.
Answered (output is not perfect, but ok for what i was needing):
import csv
from itertools import product
def main():
with open('a.csv', 'rb') as f1, open('b.csv', 'rb') as f2:
reader1 = csv.reader(f1, dialect=csv.excel_tab)
reader2 = csv.reader(f2, dialect=csv.excel_tab)
with open('output.csv', 'wb') as output:
writer = csv.writer(output, delimiter='|', dialect=csv.excel_tab)
writer.writerows(row1 + row2 for row1, row2 in product(reader1, reader2))
if __name__ == "__main__":
main()
Output file:
1|a,x
1|b,y
1|c,z
2|a,x
2|b,y
2|c,z
3|a,x
3|b,y
3|c,z
Yes the "|" is only one of the separators.
It would be nice to know how to get "1|a|x" and so on.