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

前端 未结 7 1035

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:37

    I wrote a short program that I think does what you wanted:

    It reads all lines from the reader file and then just insert them into the writer file 3 by 3 :)

    import csv
    
    def main():
    
        with open('ex.csv', 'rb') as f:
        reader = csv.reader(f)
        with open('ex2.csv', 'wb') as csvfile:
            writer = csv.writer(csvfile)
            pass_on = []
    
            for row in reader:
                #print row
    
                for c in xrange(0, len(row)): # passing on objects after count of 3
                    if row[c]:
                        pass_on.append(row[c])
    
    
            print pass_on
    
            while pass_on:
    
                writer.writerow(pass_on[:3])
                pass_on = pass_on[3:]
    
    
    
        print "done"
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题