How to transform a list into a CSV file with N items per row?

前端 未结 7 956

I want to create a new CSV file with 3 items per row. My source file looks like (there are no new lines / line breaks):

         


        
7条回答
  •  -上瘾入骨i
    2021-01-29 11:41

    A four-line solution without the csv module:

    with open('oneline_numbers.csv') as fobj_in, open('three_numbers.csv', 'w') as fobj_out:
        numbers = iter(entry.strip() for entry in next((fobj_in)).split(','))
        for line in zip(*[numbers] * 3):
            fobj_out.write(', '.join(line) + '\n')
    

提交回复
热议问题