1

I have a list of lists as below. a = [[1,2,3], [2,3,4], [3,4,5]]

I also have a separate list of names names = ['Ann', 'john', 'smith']

Now I want to write this into a csv file as below

1st row: Ann,1,2,3
2nd row: john,2,3,4
3rd row: smith,3,4,5

I am currently using;

with open(output_file, 'w') as f:
        writer = csv.writer(f)
        writer.writerows(a)

However, it does not do the job I want as it always starts from the first column, instead of the second column. Please help me.

3 Answers 3

1

The key point to understand here is that you want to process your list in parallel. This can easily be accomplished by using the built-in function zip. It takes an list of iterables, and yields the n-th element of each iterable as a tuple. You can then format your lines by using str.format:

names = ['Ann', 'john', 'smith']
sublists = [[1,2,3], [2,3,4], [3,4,5]]

with open(output_file, 'w') as file:
    for name, sublist in zip(names, sublists):
        row = '{},{},{},{}'.format(name, *sublist)
        file.write(row)

Note if your lists are different sizes, you may want to look into using itertools.zip_longest.

Sign up to request clarification or add additional context in comments.

Comments

0
with open(output_file, 'w') as f:
   f.write('\n'.join([elem[0]+','+str(elem[1]).strip('[').strip(']') for elem in zip(names,a)]))

Try this.

Comments

0
with open("output_file", 'w') as f:
    f.write("\n".join([','.join(map(str, [name] + extra)) for name, extra in zip(name, extras)])

Comments

Your Answer

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